Formatted question description: https://leetcode.ca/all/1660.html
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).
The test input is read as 3 lines:
int fromNode(not available to
int toNode(not available to
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
root is passed to
Input: root = [1,2,3], fromNode = 2, toNode = 3
Explanation: The node with value 2 is invalid, so remove it.
Input: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = 4
Explanation: The node with value 7 is invalid, so remove it and the node underneath it, node 2.
- The number of nodes in the tree is in the range
-10^9 <= Node.val <= 10^9
fromNode != toNode
toNodewill exist in the tree and will be on the same depth.
toNodeis to the right of
nullin the initial tree from the test data.
The idea is to traverse the BFS sequence. Because the error is the right pointer of a certain node, our level order traversal will change a little.
For each layer of nodes, we traverse from right to left. When traversing, we put the left and right children of the current node into the
When traversing, it is also tested whether the right child of the left/right child already exists in the hashset.
- If it exists, it means that the right pointer of the left/right child points to a node in the current layer.
- We can remove the child who points to the wrong one.