Cousins in Binary Tree - Tree - Easy - LeetCode
💻 coding

Cousins in Binary Tree - Tree - Easy - LeetCode

2 min read 301 words
2 min read
ShareWhatsAppPost on X
  • 1Cousins in a binary tree are nodes at the same depth with different parents.
  • 2The algorithm checks if two nodes with values x and y are cousins using a breadth-first search approach.
  • 3The solution has a time complexity of O(n) and a space complexity of O(height) of the tree.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Cousins in a binary tree are nodes at the same depth with different parents."

Cousins in Binary Tree - Tree - Easy - LeetCode

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

Constraints:

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

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * public int val;
 * public TreeNode left;
 * public TreeNode right;
 * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class Solution {
 public bool IsCousins(TreeNode root, int x, int y) {
 if(root == null){
 return false;
 }
 
 var queue = new Queue<TreeNode>();
 queue.Enqueue(root);
 while(queue.Count()>0){
 int count = queue.Count();
 bool foundx = false;
 bool foundy = false;
 while(count-->0){
 var node = queue.Dequeue();
 if(node.val==x){
 foundx=true;
 }
 if(node.val==y){
 foundy=true;
 } 
 
 if(node.left != null && node.right != null){
 if(node.left.val ==x && node.right.val == y){
 return false;
 }
 if(node.right.val==x && node.left.val==y){
 return false;
 }
 }
 
 if(node.left != null){
 queue.Enqueue(node.left);
 }
 if(node.right != null){
 queue.Enqueue(node.right);
 }
 
 }
 if(foundx && foundy)
 {
 return true;
 }
 }
 
 return false;
 }
}

Time Complexity: O(n)

Space Complexity: O(height)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 9 October 2020 · 2 min read · 301 words

Part of AskGif Blog · coding

You might also like

Cousins in Binary Tree - Tree - Easy - LeetCode | AskGif Blog