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}| Variable | Value |
|---|---|
root | "Node(1)" |
low | 1 |
high | 2 |
| Depth | Function Call |
|---|---|
| 1 | trimBST(Node(1), 1, 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}