Trim a Binary Search Tree
Last updated
Last updated
Input:
3
/ \
0 4
\
2
/
1
L = 1
R = 3
Output:
3
/
2
/
1class Solution {
public TreeNode trimBST(TreeNode root, int L, int R) {
if (root == null) return null;
//每一层的Condition
if (root.val < L) return trimBST(root.right, L, R);
if (root.val > R) return trimBST(root.left, L, R);
// 区间内,正常的Recursion
root.left = trimBST(root.left, L, R);
root.right = trimBST(root.right, L, R);
// 返回给parent一个区间调整完以后的subtree
return root;
}
}