Cousins in Binary Tree

Using level order traversal

Keep pushing all the children of current level to res.

If parent of target, then mark found flag as true, but don't push its children.

At the end of every level, there is a nullptr

When level ends, check if found.

If found then return res

Else reset res and add another null for further level searches.

Time Complexity: O(n)O(n)​

Space Complexity: O(2k)O(2^k)​ where k is the level where target exists.

If 'no self and sibling' condition was not given

This solution returns a vector of all the nodes that are cousins of each, including the node in question and the node's sibling

Last updated