Skip to content

Commit cee772b

Browse files
authored
Create 2096-step-by-step-directions-from-a-binary-tree-node-to-another.js
1 parent a3eda4f commit cee772b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @param {number} startValue
12+
* @param {number} destValue
13+
* @return {string}
14+
*/
15+
var getDirections = function(root, startValue, destValue) {
16+
let start = "";
17+
let end = "";
18+
19+
const traverse = (node, path) => {
20+
if (node === null) return;
21+
22+
if (node.val === startValue) start = path;
23+
if (node.val === destValue) end = path;
24+
25+
if (start !== "" && end !== "") return;
26+
if (node.left !== null) traverse(node.left, path + "L");
27+
if (node.right !== null) traverse(node.right, path + "R");
28+
}
29+
30+
traverse(root, "");
31+
32+
let skip = 0;
33+
while (start[skip] && start[skip] === end[skip]) ++skip;
34+
35+
return "U".repeat(start.length - skip) + end.substring(skip);
36+
};

0 commit comments

Comments
 (0)