JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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:

img

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

Example 2:

img

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

Example 3:

img

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

Code

DFS

class Solution {
    class Node{
        int depth;
        int parent;

        public Node(int depth, int parent) {
            this.depth = depth;
            this.parent = parent;
        }
    }
    public boolean isCousins(TreeNode root, int x, int y) {
        Node xN = find(root, x, 0);
        Node yN = find(root, y, 0);

        if(xN == null && yN == null) return true;
        if(xN == null || yN == null) return false;

        if(xN.depth != yN.depth) return false;

        return xN.parent != yN.parent;
    }

    private Node find(TreeNode root, int target, int currDepth) {
        if(root == null) return null;
        if(root.left != null && root.left.val == target) return new Node(currDepth, root.val);
        if(root.right != null && root.right.val == target) return new Node(currDepth, root.val);

        Node left = find(root.left, target, currDepth + 1);
        if(left != null) return left;

        Node right = find(root.right, target, currDepth + 1);
        if(right != null) return right;

        return null;
    }
}

BFS

class Solution {
    public boolean isCousins(TreeNode root, int x, int y) {
        if(root == null) return true;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            int size = queue.size();
            boolean isX = false;
            boolean isY = false;
            for(int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if(node.val == x) isX = true;
                if(node.val == y) isY = true;

                if(node.left != null && node.right != null) {
                    int left = node.left.val;
                    int right = node.right.val;

                    if(left == x && right == y ||
                    left == y && right == x) return false;
                }

                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }

            if(isX && isY) return true;
            if(isX || isY) return false;
        }
        return true;
    }
}