In the Correct a Binary Tree interview question, you are given the root of a binary tree that has exactly one "wrong" node. This invalid node has a right child that points to another node at the same depth but to its right, which violates the standard tree structure (it creates a cycle-like link within a level). Your task is to find this invalid node, remove it and its entire subtree, and return the corrected tree's root.
Google uses the Correct a Binary Tree coding problem to test a candidate's ability to navigate trees and handle unexpected structure violations. It evaluates your understanding of tree traversals—specifically, how to detect a "horizontal" link that shouldn't exist. It requires a solid grasp of how to update parent pointers during a traversal to effectively "prune" a branch of the tree.
The most effective Tree interview pattern for this is Breadth-First Search (BFS) or Depth-First Search (DFS) with a Right-to-Left order.
null to its parent during the recursive cleanup.Imagine a tree where:
1 has children 2 (left) and 3 (right).2 has children 4 (left) and 5 (right).3 has a right child 6.5 points to 6 (its "cousin" at the same depth).
By traversing Right-to-Left:1, then 3, then 6. Add {1, 3, 6} to visited.2, then 5.5's right child: it's 6, which is already in the set!5 is invalid. Remove it from 2.When a tree problem mentions "nodes at the same level," always consider if a Level-Order Traversal (BFS) or a specific DFS order (like Right-to-Left) simplifies the logic.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Cousins in Binary Tree II | Medium | Solve | |
| Lowest Common Ancestor of Deepest Leaves | Medium | Solve | |
| Amount of Time for Binary Tree to Be Infected | Medium | Solve | |
| All Nodes Distance K in Binary Tree | Medium | Solve | |
| Clone Binary Tree With Random Pointer | Medium | Solve |