Cousins in Binary Tree

In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.

Two nodes of a binary tree are cousins if they have the same depth, but have different parents.

We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.

Return true if and only if the nodes corresponding to the values x and y are cousins.

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

Note:

  1. The number of nodes in the tree will be between 2 and 100.
  2. Each node has a unique integer value from 1 to 100.

题目理解:

给定一棵二叉树,和两个节点,判断这两个节点是不是在同一层并且父节点不相同

解题思路:

借助容器层次遍历一次二叉树,记录两个节点的深度和他们的父节点。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    int dx, dy, px, py;
    
    public boolean isCousins(TreeNode root, int x, int y) {
        if(root == null || root.val == x || root.val == y)
            return false;
        Set<TreeNode> set = new HashSet<TreeNode>(), next;
        set.add(root);
        int depth = 0;
        while(!set.isEmpty()){
            next = new HashSet<TreeNode>();
            for(TreeNode it : set){
                if(it.val == x)
                    dx = depth;
                if(it.val == y)
                    dy = depth;
                if(it.left != null){
                    next.add(it.left);
                    if(it.left.val == x)
                        px = it.val;
                    if(it.left.val == y)
                        py = it.val;
                }
                if(it.right != null){
                    next.add(it.right);
                    if(it.right.val == x)
                        px = it.val;
                    if(it.right.val == y)
                        py = it.val;
                }
            }
            set = next;
            depth++;
        }
        return px != py && dx == dy;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37889928/article/details/88087475
今日推荐