|
| 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 | + |
| 15 | +function getDirections(root: TreeNode | null, startValue: number, destValue: number): string { |
| 16 | + const lca = (node: TreeNode | null, p: number, q: number): TreeNode | null => { |
| 17 | + if (node === null || node.val === p || node.val === q) { |
| 18 | + return node; |
| 19 | + } |
| 20 | + const left = lca(node.left, p, q); |
| 21 | + const right = lca(node.right, p, q); |
| 22 | + if (left !== null && right !== null) { |
| 23 | + return node; |
| 24 | + } |
| 25 | + return left !== null ? left : right; |
| 26 | + }; |
| 27 | + |
| 28 | + const dfs = (node: TreeNode | null, x: number, path: string[]): boolean => { |
| 29 | + if (node === null) { |
| 30 | + return false; |
| 31 | + } |
| 32 | + if (node.val === x) { |
| 33 | + return true; |
| 34 | + } |
| 35 | + path.push('L'); |
| 36 | + if (dfs(node.left, x, path)) { |
| 37 | + return true; |
| 38 | + } |
| 39 | + path[path.length - 1] = 'R'; |
| 40 | + if (dfs(node.right, x, path)) { |
| 41 | + return true; |
| 42 | + } |
| 43 | + path.pop(); |
| 44 | + return false; |
| 45 | + }; |
| 46 | + |
| 47 | + const node = lca(root, startValue, destValue); |
| 48 | + const pathToStart: string[] = []; |
| 49 | + const pathToDest: string[] = []; |
| 50 | + dfs(node, startValue, pathToStart); |
| 51 | + dfs(node, destValue, pathToDest); |
| 52 | + return 'U'.repeat(pathToStart.length) + pathToDest.join(''); |
| 53 | +} |
0 commit comments