2096. Step-By-Step Directions From a Binary Tree Node to Another
My first solution:
1. find lowest common ancestor of start and dest.
2. find path's length from LCA to start
3. find path from LCA to dest.
4. Combine startPath length's "U" with destPath's reverse.
class Solution { public String getDirections(TreeNode root, int startValue, int destValue) { TreeNode node = findLCA(root, startValue, destValue); int startLevel = findLevel(node, startValue, 0); StringBuilder s = new StringBuilder(); findPath(node, destValue, s); StringBuilder res = new StringBuilder(); for(int i=0;i){ res.append("U"); } return res.append(s).toString(); } private boolean findPath(TreeNode root, int dest,StringBuilder s){ if(root==null) return false; if(root.val==dest){ return true; } boolean left = findPath(root.left, dest, s); boolean right = findPath(root.right, dest, s); if(left){ s.insert(0,"L"); return true; } if(right){ s.insert(0,"R"); return true; } return false; } private int findLevel(TreeNode root, int start,int level){ if(root==null) return 0; if(root.val==start) return level; int left = findLevel(root.left, start, level+1); int right = findLevel(root.right, start, level+1); if(left==0) return right; else return left; } private TreeNode findLCA(TreeNode root, int start, int dest){ if(root==null) return null; if(root.val==start||root.val==dest) return root; TreeNode left = findLCA(root.left, start, dest); TreeNode right = findLCA(root.right, start, dest); if(left==null) return right; if(right==null) return left; return root; } }
My second solution:
1. find path from root to start
2. find path from root to end.
3. delete the duplicated path of the path 1 and path 2.
4. Combine startPath length's "U" with destPath's reverse.
class Solution { public String getDirections(TreeNode root, int startValue, int destValue) { StringBuilder leftPath = new StringBuilder(); StringBuilder rightPath = new StringBuilder(); getPath(root, startValue, leftPath); getPath(root, destValue, rightPath); for(int i=leftPath.length()-1, j=rightPath.length()-1;i>=0&&j>=0;i--,j--){ if(leftPath.charAt(i)==rightPath.charAt(j)){ leftPath.deleteCharAt(i); rightPath.deleteCharAt(j); } else break; } StringBuilder res = new StringBuilder(); for(int i=0;i){ res.append("U"); } res.append(rightPath.reverse()); return res.toString(); } private boolean getPath(TreeNode root, int target, StringBuilder s){ if(root==null){ return false; } if(root.val==target) return true; boolean left = getPath(root.left, target, s); boolean right = getPath(root.right, target, s); if(left){ s.append("L"); return true; }else if(right){ s.append("R"); return true; } return false; }
The two soltuions' time complexity is same, but the second one only go through the tree once, so will same more time.