KatInterview

669. Trim a Binary Search Tree

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 trim a Binary Search Tree (BST) so that all node values lie within a given range [low, high]. The relative structure of the remaining nodes must be maintained. This means if a node A is an ancestor of node B in the original tree and both survive the trim, A must remain an ancestor of B.

Solution

Trim a Binary Search Tree 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 trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
        # Base case: if the node is null, return None.
        if not root:
            return None

        # If root's value is greater than high, the new root must be in the left subtree
        # because of the BST property. The right subtree and the root itself are trimmed.
        if root.val > high:
            return self.trimBST(root.left, low, high)
        
        # If root's value is less than low, the new root must be in the right subtree
        # because of the BST property. The left subtree and the root itself are trimmed.
        if root.val < low:
            return self.trimBST(root.right, low, high)
            
        # If root's value is within the range [low, high], we keep the root.
        # Then, we recursively trim its left and right subtrees.
        # The connections are updated with the results of the recursive calls.
        root.left = self.trimBST(root.left, low, high)
        root.right = self.trimBST(root.right, low, high)
        
        # Return the current node as it is the valid root of the trimmed subtree.
        return root

Trim a Binary Search Tree 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 trimBST(TreeNode root, int low, int high) {
        // Base case: if the node is null, return null.
        if (root == null) {
            return null;
        }

        // If root's value is greater than high, the new root must be in the left subtree
        // because of the BST property. The right subtree and the root itself are trimmed.
        if (root.val > high) {
            return trimBST(root.left, low, high);
        }
        
        // If root's value is less than low, the new root must be in the right subtree
        // because of the BST property. The left subtree and the root itself are trimmed.
        if (root.val < low) {
            return trimBST(root.right, low, high);
        }

        // If root's value is within the range [low, high], we keep the root.
        // Then, we recursively trim its left and right subtrees.
        // The connections are updated with the results of the recursive calls.
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        
        // Return the current node as it is the valid root of the trimmed subtree.
        return root;
    }
}

Trim a Binary Search Tree 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:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        // Base case: if the node is null, return null.
        if (!root) {
            return nullptr;
        }

        // If root's value is greater than high, the new root must be in the left subtree
        // because of the BST property. The right subtree and the root itself are trimmed.
        if (root->val > high) {
            return trimBST(root->left, low, high);
        }
        
        // If root's value is less than low, the new root must be in the right subtree
        // because of the BST property. The left subtree and the root itself are trimmed.
        if (root->val < low) {
            return trimBST(root->right, low, high);
        }

        // If root's value is within the range [low, high], we keep the root.
        // Then, we recursively trim its left and right subtrees.
        // The connections are updated with the results of the recursive calls.
        root->left = trimBST(root->left, low, high);
        root->right = trimBST(root->right, low, high);
        
        // Return the current node as it is the valid root of the trimmed subtree.
        return root;
    }
};

Trim a Binary Search Tree 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 trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
    // Base case: if the node is null, return null.
    if (root === null) {
        return null;
    }

    // If root's value is greater than high, the new root must be in the left subtree
    // because of the BST property. The right subtree and the root itself are trimmed.
    if (root.val > high) {
        return trimBST(root.left, low, high);
    }
    
    // If root's value is less than low, the new root must be in the right subtree
    // because of the BST property. The left subtree and the root itself are trimmed.
    if (root.val < low) {
        return trimBST(root.right, low, high);
    }

    // If root's value is within the range [low, high], we keep the root.
    // Then, we recursively trim its left and right subtrees.
    // The connections are updated with the results of the recursive calls.
    root.left = trimBST(root.left, low, high);
    root.right = trimBST(root.right, low, high);
    
    // Return the current node as it is the valid root of the trimmed subtree.
    return 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.