1660. Correct a Binary Tree π
Description
You have a binary tree with a small defect. There is exactly one invalid node where its right child incorrectly points to another node at the same depth but to the invalid node's right.
Given the root of the binary tree with this defect, root, return the root of the binary tree after removing this invalid node and every node underneath it (minus the node it incorrectly points to).
Custom testing:
The test input is read as 3 lines:
TreeNode rootint fromNode(not available tocorrectBinaryTree)int toNode(not available tocorrectBinaryTree)
After the binary tree rooted at root is parsed, the TreeNode with value of fromNode will have its right child pointer pointing to the TreeNode with a value of toNode. Then, root is passed to correctBinaryTree.
Example 1:
Input: root = [1,2,3], fromNode = 2, toNode = 3 Output: [1,null,3] Explanation: The node with value 2 is invalid, so remove it.
Example 2:
Input: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = 4 Output: [8,3,1,null,null,9,4,null,null,5,6] Explanation: The node with value 7 is invalid, so remove it and the node underneath it, node 2.
Constraints:
- The number of nodes in the tree is in the range
[3, 104]. -109 <= Node.val <= 109- All
Node.valare unique. fromNode != toNodefromNodeandtoNodewill exist in the tree and will be on the same depth.toNodeis to the right offromNode.fromNode.rightisnullin the initial tree from the test data.
Solutions
Solution 1: DFS
Thinking
Exactly one right pointer wrongly aims at a same-level node to its right; we delete that bad node and its subtree. In a left-to-right visit the target of the bad edge is seen before its source.
A preorder that goes right then left: if the current right child is already in the visited set, this node is the error and we return null to cut it off.
A set \(\textit{vis}\) records visited nodes; the recursion writes back the (possibly null) children.
We design a function dfs(root) to handle the subtree with root as the root. If root is null or root.right has been visited, root is an invalid node, so we return null. Otherwise, we recursively process root.right and root.left, and return root.
Finally, we return dfs(root).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |

