Trim a Binary Search Tree — LeetCode 669 Python Solution
- Problem
- #669
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant).
Example
- Input
- root = [1,0,2], low = 1, high = 2
- Output
- [1,null,2]
Python solution
# 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 trimBST(
self, root: Optional[TreeNode], low: int, high: int
) -> Optional[TreeNode]:
def dfs(root):
if root is None:
return root
if root.val > high:
return dfs(root.left)
if root.val < low:
return dfs(root.right)
root.left = dfs(root.left)
root.right = dfs(root.right)
return root
return dfs(root)Complexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 669. Trim a Binary Search Tree is filed here because LeetCode tags it Tree, Binary Tree and Binary Search 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 669. Trim a Binary Search Tree?
- LeetCode 669. Trim a Binary Search Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 669. Trim a Binary Search Tree?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 669. Trim a Binary Search Tree?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 669. Trim a Binary Search Tree cover?
- LeetCode 669. Trim a Binary Search Tree is tagged Tree, Depth-First Search, Binary Search Tree and Binary Tree on LeetCode.