|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * function TreeNode(val) { |
| 4 | + * this.val = val; |
| 5 | + * this.left = this.right = null; |
| 6 | + * } |
| 7 | + */ |
| 8 | +/** |
| 9 | + * @param {TreeNode} root |
| 10 | + * @param {number} x |
| 11 | + * @param {number} y |
| 12 | + * @return {boolean} |
| 13 | + */ |
| 14 | +const isCousins = function(root, x, y) { |
| 15 | + if(root == null) return false |
| 16 | + const res = [] |
| 17 | + chk(root, x, [], res) |
| 18 | + chk(root, y, [], res) |
| 19 | + if(res.length < 2) return false |
| 20 | + return chkRes(res, x, y) |
| 21 | +}; |
| 22 | +function chkRes(arr, x, y) { |
| 23 | + let ci = 0, xi = -1, yi = -1 |
| 24 | + let len = Math.max(arr[0].length, arr[1].length) |
| 25 | + for(let i = 0; i < len; i++) { |
| 26 | + if(arr[0][i] === arr[1][i]) ci = i |
| 27 | + if(arr[0][i] === x || arr[1][i] === x) xi = i |
| 28 | + if(arr[0][i] === y || arr[1][i] === y) yi = i |
| 29 | + } |
| 30 | + if(xi - yi === 0 && xi - ci > 1) { |
| 31 | + return true |
| 32 | + } else { |
| 33 | + return false |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function chk(node, val, path, res) { |
| 38 | + if(node == null) return |
| 39 | + path.push(node.val) |
| 40 | + if(node.val === val) { |
| 41 | + res.push(path.slice(0)) |
| 42 | + return |
| 43 | + } |
| 44 | + chk(node.left, val, path.slice(0), res) |
| 45 | + chk(node.right, val, path.slice(0), res) |
| 46 | +} |
0 commit comments