993. 二叉树的堂兄弟节点
在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。
如果二叉树的两个节点深度相同,但 父节点不同 ,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root ,以及树中两个不同节点的值 x 和 y 。
只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true 。否则,返回 false。
链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
   | 
 
 
 
 
 
 
 
 
 
 
 
 
  var isCousins = function(root, x, y) {   if (root === null) return false   const nodeQue = [root]   while(nodeQue.length) {     const nodes = nodeQue.splice(0)     const len = nodes.length     let xnode = null, ynode = null;     for(let i = 0; i < len; i++) {       const node = nodes[i]       if (node) {         if (x === node.val) {           xnode = node         } else if (y === node.val) {           ynode = node         }         if (node.left) {           node.left.parent = node           nodeQue.push(node.left)         }         if (node.right) {           node.right.parent = node           nodeQue.push(node.right)         }       }     }     if (xnode !== null && ynode !== null && xnode.parent !== ynode.parent) {       return true     } else if (xnode === null && ynode === null) {       continue     } else {       return false     }   }   return false };
 
  |