Trim a Binary Search Tree
Given a binary search tree and the lowest and highest boundaries asLandR, 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
Example 1:
Input:
1
/ \
0 2
L = 1
R = 2
Output:
1
\
2Example 2:
Note
这题做法有些取巧,并不是真正意义上在内存里面删除不符合区间的Node,只是将Node的指向进行的更改,大致思路:
每一层的Condition有三种:
root.val小于区间的lower boundL,则返回root.rightsubtree传上来的root,这里就变相的'删除'掉了当前root和所有
root.left的noderoot.val大于区间的upper boundR,则返回root.leftsubtree传上来的root满足区间,则继续递归
当递归走到叶子节点的时候,我们向上返回root,这里return root的定义是:
返回给parent一个区间调整完以后的subtree
Code
Last updated