Skip to content

Commit 898df56

Browse files
committed
Daily Solutions With JS
1 parent 31fe037 commit 898df56

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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

Comments
 (0)