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 afterremoving 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 root
int 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.
****
Input: root =[1,2,3], fromNode =2, toNode =3Output: [1,null,3]Explanation: The node with value 2is invalid, so remove it.
Example 2:
1
2
3
4
****
Input: root =[8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode =7, toNode =4Output: [8,3,1,null,null,9,4,null,null,5,6]Explanation: The node with value 7is invalid, so remove it and the node underneath it, node 2.
Constraints:
The number of nodes in the tree is in the range [3, 10^4].
-109 <= Node.val <= 10^9
All Node.val are unique.
fromNode != toNode
fromNode and toNode will exist in the tree and will be on the same depth.
toNode is to the right of fromNode.
fromNode.right is null in the initial tree from the test data.
The invalid node’s right child points to another node at the same depth but to its right. If we traverse the tree level by level (BFS) from right to left, we can use a set to track all nodes seen so far at the current level. When we find a node whose right child is already in the set, that node is the invalid one and should be removed.