Correct a Binary Tree — LeetCode 1660 Python Solution
MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchHash TableBinary Tree
- Problem
- #1660
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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
LeetCode 653Two Sum IV - Input is a BSTEasyLeetCode 863All Nodes Distance K in Binary TreeMediumLeetCode 865Smallest Subtree with all the Deepest NodesMediumLeetCode 987Vertical Order Traversal of a Binary TreeHardLeetCode 1123Lowest Common Ancestor of Deepest LeavesMediumLeetCode 1261Find Elements in a Contaminated Binary TreeMedium
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.