Split BST — LeetCode 776 Python Solution
- Problem
- #776
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary search tree (BST) and an integer target, split the tree into two subtrees where the first subtree has nodes that are all smaller or equal to the target value, while the second subtree has all nodes that are greater than the target value. It is not necessarily the case that the tree contains a node with the value target.
Example
- Input
- root = [4,2,6,1,3,5,7], target = 2
- Output
- [[2,1],[4,3,6,null,null,5,7]]
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 splitBST(
self, root: Optional[TreeNode], target: int
) -> List[Optional[TreeNode]]:
def dfs(root):
if root is None:
return [None, None]
if root.val <= target:
l, r = dfs(root.right)
root.right = l
return [root, r]
else:
l, r = dfs(root.left)
root.left = r
return [l, root]
return dfs(root)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(h) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 776. Split BST is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Tree, Binary Tree and Binary Search Tree.
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 776. Split BST?
- LeetCode 776. Split BST is rated Medium on LeetCode.
- What is the time complexity of LeetCode 776. Split BST?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 776. Split BST?
- The Python solution on this page uses O(h) auxiliary space.
- What topics does LeetCode 776. Split BST cover?
- LeetCode 776. Split BST is tagged Tree, Binary Search Tree, Recursion and Binary Tree on LeetCode.
- Is LeetCode 776. Split BST a premium problem?
- Yes. LeetCode 776. Split BST is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.