Leetcode Problem 993. Cousins in Binary Tree

993. Cousins in Binary Tree

Leetcode Solutions

Breadth First Search with Early Stopping

  1. Initialize a queue and add the root node to it.
  2. While the queue is not empty, perform the following steps: a. Initialize two flags, foundX and foundY, to false. b. For each level, iterate over the nodes in the queue. c. For each node, check if its children are x or y.
    • If one child is x, set foundX to true.
    • If one child is y, set foundY to true. d. If both foundX and foundY are true at the end of the level, return true. e. If only one is found, continue to the next level.
  3. If both nodes are not found at the same level, return false.
UML Thumbnail

Depth First Search with Parent and Depth Tracking

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...