KatInterview

791. Split BST

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to split a Binary Search Tree (BST) into two separate subtrees based on a given target value. The first subtree should contain all nodes with values less than or equal to the target, and the second subtree should contain all nodes with values greater than the target. A key constraint is that the relative structure of the original tree should be preserved as much as possible. This means if two nodes were in a parent-child relationship and end up in the same subtree after the split, they should maintain that relationship.

Solution

Split BST in 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]]:
        # Base case: if the tree is empty, both resulting trees are empty.
        if not root:
            return [None, None]
        
        # If the root's value is less than or equal to the target.
        if root.val <= target:
            # The root and its entire left subtree belong to the "smaller or equal" part.
            # We need to check the right subtree, as it might contain nodes
            # that are also <= target.
            sub_split = self.splitBST(root.right, target)
            
            # The smaller part from the split right subtree now becomes the new right child of the root.
            # All nodes in sub_split[0] are > root.val and <= target.
            root.right = sub_split[0]
            
            # The result is the current root (with its modified right child) and the larger part from the split right subtree.
            return [root, sub_split[1]]
        else:  # root.val > target
            # The root and its entire right subtree belong to the "greater than" part.
            # We need to check the left subtree, as it might contain nodes
            # that are > target.
            sub_split = self.splitBST(root.left, target)
            
            # The larger part from the split left subtree now becomes the new left child of the root.
            # All nodes in sub_split[1] are < root.val and > target.
            root.left = sub_split[1]
            
            # The result is the smaller part from the split left subtree and the current root (with its modified left child).
            return [sub_split[0], root]

Split BST in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode[] splitBST(TreeNode root, int target) {
        // Base case: if the tree is empty, both resulting trees are empty.
        if (root == null) {
            return new TreeNode[]{null, null};
        }

        // If the root's value is less than or equal to the target.
        if (root.val <= target) {
            // The root and its entire left subtree belong to the "smaller or equal" part.
            // We need to check the right subtree, as it might contain nodes
            // that are also <= target.
            TreeNode[] sub_split = splitBST(root.right, target);
            
            // The smaller part from the split right subtree now becomes the new right child of the root.
            // All nodes in sub_split[0] are > root.val and <= target.
            root.right = sub_split[0];
            
            // The result is the current root (with its modified right child) and the larger part from the split right subtree.
            return new TreeNode[]{root, sub_split[1]};
        } else { // root.val > target
            // The root and its entire right subtree belong to the "greater than" part.
            // We need to check the left subtree, as it might contain nodes
            // that are > target.
            TreeNode[] sub_split = splitBST(root.left, target);
            
            // The larger part from the split left subtree now becomes the new left child of the root.
            // All nodes in sub_split[1] are < root.val and > target.
            root.left = sub_split[1];
            
            // The result is the smaller part from the split left subtree and the current root (with its modified left child).
            return new TreeNode[]{sub_split[0], root};
        }
    }
}

Split BST in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> splitBST(TreeNode* root, int target) {
        // Base case: if the tree is empty, both resulting trees are empty.
        if (!root) {
            return {nullptr, nullptr};
        }

        // If the root's value is less than or equal to the target.
        if (root->val <= target) {
            // The root and its entire left subtree belong to the "smaller or equal" part.
            // We need to check the right subtree, as it might contain nodes
            // that are also <= target.
            vector<TreeNode*> sub_split = splitBST(root->right, target);
            
            // The smaller part from the split right subtree now becomes the new right child of the root.
            // All nodes in sub_split[0] are > root->val and <= target.
            root->right = sub_split[0];
            
            // The result is the current root (with its modified right child) and the larger part from the split right subtree.
            return {root, sub_split[1]};
        } else { // root->val > target
            // The root and its entire right subtree belong to the "greater than" part.
            // We need to check the left subtree, as it might contain nodes
            // that are > target.
            vector<TreeNode*> sub_split = splitBST(root->left, target);
            
            // The larger part from the split left subtree now becomes the new left child of the root.
            // All nodes in sub_split[1] are < root->val and > target.
            root->left = sub_split[1];
            
            // The result is the smaller part from the split left subtree and the current root (with its modified left child).
            return {sub_split[0], root};
        }
    }
};

Split BST in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function splitBST(root: TreeNode | null, target: number): Array<TreeNode | null> {
    // Base case: if the tree is empty, both resulting trees are empty.
    if (!root) {
        return [null, null];
    }

    // If the root's value is less than or equal to the target.
    if (root.val <= target) {
        // The root and its entire left subtree belong to the "smaller or equal" part.
        // We need to check the right subtree, as it might contain nodes
        // that are also <= target.
        const sub_split = splitBST(root.right, target);
        
        // The smaller part from the split right subtree now becomes the new right child of the root.
        // All nodes in sub_split[0] are > root.val and <= target.
        root.right = sub_split[0];
        
        // The result is the current root (with its modified right child) and the larger part from the split right subtree.
        return [root, sub_split[1]];
    } else { // root.val > target
        // The root and its entire right subtree belong to the "greater than" part.
        // We need to check the left subtree, as it might contain nodes
        // that are > target.
        const sub_split = splitBST(root.left, target);
        
        // The larger part from the split left subtree now becomes the new left child of the root.
        // All nodes in sub_split[1] are < root.val and > target.
        root.left = sub_split[1];
        
        // The result is the smaller part from the split left subtree and the current root (with its modified left child).
        return [sub_split[0], root];
    }
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.