AlgoMaster Logo

Trim Binary Search Tree

tree=[1, 0, 2, -1],low=1,high=2
1public TreeNode trimBST(TreeNode root, int low, int high) {
2    return trim(root, low, high);
3}
4
5private TreeNode trim(TreeNode node, int low, int high) {
6    if (node == null) {
7        return null;
8    }
9
10    // Node value < low, trim to right subtree
11    if (node.val < low) {
12        return trim(node.right, low, high);
13    }
14
15    // Node value > high, trim to left subtree
16    if (node.val > high) {
17        return trim(node.left, low, high);
18    }
19
20    // Node in range, trim both subtrees
21    node.left = trim(node.left, low, high);
22    node.right = trim(node.right, low, high);
23    return node;
24}
0 / 16
L102-1