Problem
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given a binary tree made of positive integers where every node have unique values which is greater than 1.
If we get two integer values x and y, return TRUE if and only if the nodes corresponding to x and y are cousins otherwise return FALSE.
Solution
We can solve the problem by using any tree traversing mechanism. We just need to keep track of the parent of the node as well as the depth level of the node.
In the sample code we are using pre order traversal where we are looking at the node first followed by left and the right node.
Comments
Post a Comment