May 07, 2020

#LeetCode: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.
Java Solution 1

Algorithm
1). Compare the depth of both the nodes.
2). If depth is equal, check if the nodes are siblings or not.
3). If the nodes are not siblings return true.


Java Solution 2 : Using DFS



ALSO CHECKOther LeetCode Solutions in Java

-K Himaanshu Shuklaa..

No comments:

Post a Comment