方法
先找到最近公共祖先,然后分别向下dfs,直到遇到dest或者source,同时记录路径。再把路径反过来,拼接。
class Solution {
StringBuffer ps = new StringBuffer(); // 到source的路径
StringBuffer pd = new StringBuffer(); // 到dest的路径
StringBuffer res = new StringBuffer();
public String getDirections(TreeNode root, int startValue, int destValue) {
TreeNode lca = getLCA(root, startValue, destValue);
pathToSrc(lca, startValue);
pathToDest(lca, destValue);
return res.toString();
}
// 找从lca到source的路径
public void pathToSrc(TreeNode node, int val) {
if (node == null) {
return;
}
if (node.val == val) {
res.append(ps); // no need to reverse, records "U"s
return;
}
ps.append("U");
pathToSrc(node.left, val);
ps.deleteCharAt(ps.length() - 1);
ps.append("U");
pathToSrc(node.right, val);
ps.deleteCharAt(ps.length() - 1);
}
// 找从lca到dest的路径
public void pathToDest(TreeNode node, int val) {
if (node == null) {
return;
}
if (node.val == val) {
res.append(pd);
return;
}
pd.append("L");
pathToDest(node.left, val);
pd.deleteCharAt(pd.length() - 1);
pd.append("R");
pathToDest(node.right, val);
pd.deleteCharAt(pd.length() - 1);
}
// 找出两个数的最近公共祖先
public TreeNode getLCA(TreeNode root, int val1, int val2) {
if (root == null || root.val == val1 || root.val == val2) {
return root;
}
TreeNode left = getLCA(root.left, val1, val2);
TreeNode right = getLCA(root.right, val1, val2);
if (left != null && right != null) {
return root;
} else if (left != null & right == null) {
return left;
} else if (left == null & right != null) {
return right;
} else {
return null;
}
}
}