Split BST — LeetCode 776 Python Solution

MediumLeetCode PremiumTreeBinary Search TreeRecursionBinary Tree
Problem
#776
Reading time
4 min

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

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 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

MeasureComplexity
TimeO(n)
SpaceO(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.

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