Leetcode #776: Split BST
In this guide, we solve Leetcode #776 Split BST in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Tree, Binary Search Tree, Recursion, Binary Tree
Intuition
The input is a tree, so recursive decomposition is a natural fit.
We can compute the answer by combining results from left and right subtrees.
Approach
Use DFS and pass the required state through recursive calls.
Combine child results to compute the answer for each node.
Steps:
- Pick traversal order.
- Recurse with state.
- Combine results from children.
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
The time complexity is O(n). The space complexity is O(h).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.