This problem involves identifying and correcting a single defect in a binary tree. The defect is that exactly one node's right child points incorrectly to another node at the same depth. The goal is to remove the invalid node and its subtree, leaving the correctly pointed-to node intact.
Approach:
The most efficient approach uses Depth-First Search (DFS). We traverse the tree recursively, marking visited nodes to prevent infinite loops. The core logic lies in identifying the invalid node:
Base Case: If a node is null
(empty) or its right child has already been visited, this indicates we've reached the invalid node or a node below it. We return null
to effectively remove this part of the tree.
Recursive Steps: Otherwise, we mark the current node as visited, recursively process its right and left subtrees, and then return the current node. This ensures that only the invalid node and its subtree are removed.
Time and Space Complexity Analysis:
Time Complexity: O(N), where N is the number of nodes in the tree. This is because we visit each node at most once during the DFS traversal.
Space Complexity: O(N) in the worst case. This is due to the recursive call stack during the DFS. In the worst case, the depth of the tree could be N (a skewed tree), leading to a call stack of size N. The vis
set (or equivalent data structure) also uses O(N) space to store visited nodes.
Code Implementation (Python):
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def correctBinaryTree(self, root: TreeNode) -> TreeNode:
visited = set() # Set to track visited nodes
def dfs(node):
if node is None or node.right in visited:
return None # Invalid node or subtree below
visited.add(node) # Mark as visited
node.right = dfs(node.right) # Process right subtree
node.left = dfs(node.left) # Process left subtree
return node # Return the corrected node
return dfs(root)
The code in other languages (Java, C++, JavaScript) follows a very similar structure, utilizing a Set
(or equivalent) to track visited nodes and recursively performing DFS to identify and correct the invalid subtree. The core algorithm remains consistent across languages.