Skip to content

Commit 24027fa

Browse files
committed
feat: add ts solution to lc problem: No. 2096
1 parent f583f51 commit 24027fa

File tree

1 file changed

+42
-0
lines changed
  • solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* val: number
5+
* left: TreeNode | null
6+
* right: TreeNode | null
7+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
* }
13+
*/
14+
export function getDirections(root: TreeNode | null, start: number, dest: number): string {
15+
const dfs = (node: TreeNode | null, x: number, path: string[] = []): boolean => {
16+
if (!node) return false;
17+
if (node.val === x) return true;
18+
19+
path.push('L');
20+
if (dfs(node.left, x, path)) return true;
21+
22+
path[path.length - 1] = 'R';
23+
if (dfs(node.right, x, path)) return true;
24+
path.pop();
25+
26+
return false;
27+
};
28+
29+
const startPath: string[] = [];
30+
const destPath: string[] = [];
31+
dfs(root, start, startPath);
32+
dfs(root, dest, destPath);
33+
34+
let i = 0;
35+
while (startPath[i] === destPath[i]) i++;
36+
37+
return (
38+
Array(startPath.length - i)
39+
.fill('U')
40+
.join('') + destPath.slice(i).join('')
41+
);
42+
}

0 commit comments

Comments
 (0)