Correct a Binary Tree Problem
Description
LeetCode Problem 1660.
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, 10^4]. -10^9 <= Node.val <= 10^9- 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.
Solution
Approach: DFS, Right Child First
The bad node's right child points to a node at the same depth on its right. If we visit each level from right to left, that node has already been seen when we reach the bad node.
So run a DFS that visits the right subtree before the left one, keeping a set vis of visited nodes. dfs(root) returns null if root is null or if root.right is already in vis (then root is the invalid node, and returning null removes it with its whole subtree). Otherwise it adds root to vis, sets root.right = dfs(root.right) and root.left = dfs(root.left), and returns root.
The answer is dfs(root).
Complexity: O(n) time and O(n) space, where n is the number of nodes in the tree.
# 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:
def dfs(root):
if root is None or root.right in vis:
return None
vis.add(root)
root.right = dfs(root.right)
root.left = dfs(root.left)
return root
vis = set()
return dfs(root)