|
| 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