993. Cousins in Binary Tree - Easy

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 xand 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.

 

level order traversal,用两个flag分别表示X、Y是否存在:hasX, hasY

每一层开始时把hasX, hasY重置,如果这一层同时存在X、Y,还要判断它们是否是同一个parent,如果不是则继续traversal。如果遍历一层后,X、Y同时存在,且不是同一个parent,返回true

time = O(n), space = O(n) worst case

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isCousins(TreeNode root, int x, int y) {
        if(root == null) {
            return false;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()) {
            int size = q.size();
            boolean hasX = false, hasY = false;
            for(int i = 0; i < size; i++) {
                TreeNode cur = q.poll();
                if(cur.val == x) {
                    hasX = true;
                }
                if(cur.val == y) {
                    hasY = true;
                }
                if(cur.left != null && cur.right != null) {
                    if(cur.left.val == x && cur.right.val == y) {
                        return false;
                    }
                    if(cur.left.val == y && cur.right.val == x) {
                        return false;
                    }
                }
                if(cur.left != null) {
                    q.offer(cur.left);
                }
                if(cur.right != null) {
                    q.offer(cur.right);
                }
            }
            if(hasX && hasY) {
                return true;
            }
        }
        return false;
    }
}

 

posted @ 2019-07-09 09:15  fatttcat  阅读(168)  评论(0编辑  收藏  举报