|
| 1 | +var getDirections = function(root, startValue, destValue) { |
| 2 | + const lca = findLCA(root, startValue, destValue) |
| 3 | + const depth = findDepth(lca, startValue) |
| 4 | + const path = findPath(lca, destValue) |
| 5 | + return 'U'.repeat(depth).concat(path) |
| 6 | +}; |
| 7 | + |
| 8 | +function findLCA(root, s, d){ |
| 9 | + if(!root) return null |
| 10 | + if(root.val === s || root.val === d) return root |
| 11 | + const left = findLCA(root.left, s, d) |
| 12 | + const right = findLCA(root.right, s, d) |
| 13 | + if(left && right) |
| 14 | + return root |
| 15 | + return left || right |
| 16 | +} |
| 17 | + |
| 18 | +function findDepth(root, val, count=0){ |
| 19 | + if(!root) return 0 |
| 20 | + if(root.val === val) return count |
| 21 | + return findDepth(root.left, val, count+1) || |
| 22 | + findDepth(root.right, val, count+1) |
| 23 | +} |
| 24 | + |
| 25 | +function findPath(root, val, str=''){ |
| 26 | + if(!root) return '' |
| 27 | + if(root.val === val) return str |
| 28 | + return findPath(root.left, val, str+'L') || |
| 29 | + findPath(root.right, val, str+'R') |
| 30 | +}; |
0 commit comments