Correct a Binary Tree — LeetCode 1660 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchHash TableBinary Tree
Problem
#1660
Reading time
3 min

The problem

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.

Example

Input
root = [1,2,3], fromNode = 2, toNode = 3
Output
[1,null,3]
Explanation
The node with value 2 is invalid, so remove it.

Python solution

Python
# 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)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1660. Correct a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1660. Correct a Binary Tree?
LeetCode 1660. Correct a Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 1660. Correct a Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1660. Correct a Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1660. Correct a Binary Tree cover?
LeetCode 1660. Correct a Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table and Binary Tree on LeetCode.
Is LeetCode 1660. Correct a Binary Tree a premium problem?
Yes. LeetCode 1660. Correct a Binary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview