In a binary tree, the root node is at depth
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the
Return
Example 1:
Example 2:
Example 3:
Note:
- The number of nodes in the tree will be between
2 and100 . - Each node has a unique integer value from
1 to100 .
* Images Source : LeetCode
Solution
Here we can perform level order traversal to check if
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isCousins(TreeNode root, int x, int y) { if(root==null) return false; boolean xExstFlg=false,yExstFlg=false; Queue<TreeNode> queue=new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()){ int size=queue.size(); xExstFlg=false; yExstFlg=false; for(int i=0;i<size;i++){ TreeNode curr=queue.poll(); if(curr.val==x) xExstFlg=true; if(curr.val==y) yExstFlg=true; if((curr.left!=null && curr.right!=null) && ((curr.left.val==x && curr.right.val==y)|| (curr.left.val==y && curr.right.val==x))){ return false; } if(curr.left!=null) queue.offer(curr.left); if(curr.right!=null) queue.offer(curr.right); } if(xExstFlg && yExstFlg) return true; } return false; } } |
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.