507. Correct a Binary Tree

Given the root of a binary tree with n nodes, each node contains a unique integer value. However, exactly one node has an incorrect right child that points to another node at the same level instead of nullptr.

The task is to correct the tree by removing the incorrectly assigned right child and return the corrected tree.

The test input is read as 3 lines:

  • TreeNode root
  • int fromNode (not passed to correctBinaryTree)
  • int toNode (not passed to correctBinaryTree)

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.

Now Your Turn!

Pick the correct output for the given input

Input: root = [10,5,15,3,7,null,18,1,4,null,null,6,null,null,null], fromNode = 7, toNode = 18

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [3, 104].
  • -109 <= Node.val <= 109
  • 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.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/**
* Definition for a binary tree node.
* class TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
 
class Solution {
public:
TreeNode* correctBinaryTree(TreeNode* root) {
}
};
Test Case

Input:

From Node
Root
To Node