We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。
0
k
k+1
如果二叉树的两个节点深度相同,但 父节点不同,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root,以及树中两个不同节点的值 x 和 y。
root
x
y
只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true。否则,返回 false。
true
false
Input: root = [1,2,3,4], x = 4, y = 3 Output: false
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 Output: true
Input: root = [1,2,3,null,4], x = 2, y = 3 Output: false
The text was updated successfully, but these errors were encountered:
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {number} x * @param {number} y * @return {boolean} */ var isCousins = function(root, x, y) { let xPosition; let yPosition; const queue = [[-1, 0, root]]; while(queue.length !== 0) { const [father, depth, node] = queue.shift(); if (node.val === x) { xPosition = [father, depth]; } if (node.val === y) { yPosition = [father, depth]; } if (node.left) { queue.push([node.val, depth + 1, node.left]); } if (node.right) { queue.push([node.val, depth + 1, node.right]); } } return xPosition[1] === yPosition[1] && xPosition[0] !== yPosition[0]; };
Sorry, something went wrong.
No branches or pull requests
993. Cousins in Binary Tree
在二叉树中,根节点位于深度
0
处,每个深度为k
的节点的子节点位于深度k+1
处。如果二叉树的两个节点深度相同,但 父节点不同,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点
root
,以及树中两个不同节点的值x
和y
。只有与值
x
和y
对应的节点是堂兄弟节点时,才返回true
。否则,返回false
。Example 1
Example 2
Example 3
The text was updated successfully, but these errors were encountered: