Skip to content
New issue

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

993. Cousins in Binary Tree #149

Open
Tcdian opened this issue May 7, 2020 · 1 comment
Open

993. Cousins in Binary Tree #149

Tcdian opened this issue May 7, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 7, 2020

993. Cousins in Binary Tree

在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。

如果二叉树的两个节点深度相同,但 父节点不同,则它们是一对堂兄弟节点。

我们给出了具有唯一值的二叉树的根节点 root,以及树中两个不同节点的值 xy

只有与值 xy 对应的节点是堂兄弟节点时,才返回 true。否则,返回 false

Example 1

Input: root = [1,2,3,4], x = 4, y = 3
Output: false

Example 2

Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true

Example 3

Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
@Tcdian
Copy link
Owner Author

Tcdian commented May 7, 2020

Solution

  • JavaScript Solution
/**
 * 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];
};

@Tcdian Tcdian added the Tree label May 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant