|
| 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} x |
| 12 | + * @param {number} y |
| 13 | + * @return {boolean} |
| 14 | + */ |
| 15 | + |
| 16 | +interface Cache { |
| 17 | + [key: number]: Child; |
| 18 | +} |
| 19 | + |
| 20 | +interface Child { |
| 21 | + parent?: number; |
| 22 | + depth: number; |
| 23 | +} |
| 24 | + |
| 25 | +export const isCousins = function (root, x, y): boolean { |
| 26 | + const cache: Cache = {}; |
| 27 | + |
| 28 | + if (root && root.val) cache[root.val] = { parent: null, depth: 0 }; |
| 29 | + |
| 30 | + const dfs = (node, depth: number = 1): void => { |
| 31 | + if (node && node.left) { |
| 32 | + cache[node.left.val] = { parent: node.val, depth }; |
| 33 | + dfs(node.left, depth + 1); |
| 34 | + } |
| 35 | + |
| 36 | + if (node && node.right) { |
| 37 | + cache[node.right.val] = { parent: node.val, depth }; |
| 38 | + dfs(node.right, depth + 1); |
| 39 | + } |
| 40 | + }; |
| 41 | + |
| 42 | + if (root) dfs(root); |
| 43 | + else return false; |
| 44 | + |
| 45 | + const depthOfx: number = cache[x].depth; |
| 46 | + const depthOfy: number = cache[y].depth; |
| 47 | + const parentOfx: number = cache[x].parent; |
| 48 | + const parentOfy: number = cache[y].parent; |
| 49 | + |
| 50 | + return depthOfx === depthOfy && parentOfx !== parentOfy; |
| 51 | +}; |
0 commit comments