0993. Cousins in Binary Tree
Easy | Tree + Level-order Traversal | 24 ms (97.60%), 14.1 MB (97.24%)
Source: LeetCode - Cousins in Binary Tree GitHub: Solution / Performance
Given the root
of a binary tree with unique values and the values of two different nodes of the tree x
and y
, return true
if the nodes corresponding to the values x
and y
in the tree are cousins, or false
otherwise.
Two nodes of a binary tree are cousins if they have the same depth with different parents.
Note that in a binary tree, the root node is at depth 0, and children of each depth k
node are at the depth k + 1
.
Extension question of Level-order traversal.
While traversing the tree in level order, we need additional information:
Whenever we append a node onto the stack, we need to record its parent node.
We need to know which level (depth) we are at since cousin nodes exist in the same depth. That is to say, if we only find one node instead of two nodes, there is no cousin node existing.
Last updated