Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
Example 1:123456789101112Input: 1 / \ 0 2 L = 1 R = 2Output: 1 \ 2
Example 2:1234567891011121314151617Input: 3 / \ 0 4 \ 2 / 1 L = 1 R = 3Output: 3 / 2 /
解法1: Recursion
应用BST的性质,如果当前是一个leaf并且不在[L,R]范围内,那么就返回null。
如果不是leaf并且leaf的value在范围内,那么就对左右子树各trim
如果不是leaf而不在范围内,那么就either对左子数或者右子数trim就可以了。
|
|