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