題目
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:
Input:
1
/ \
0 2
L = 1
R = 2
Output:
1
\
2
Example 2:
Input:
3
/ \
0 4
\
2
/
1
L = 1
R = 3
Output:
3
/
2
/
1
難度
Easy
方法
采用遞歸的方法婚苹。如果root
為空岸更,則直接返回root
; 如果root
的值<L
,表示root
及其左子樹所有節(jié)點都<L
膊升,那么需要改變root
節(jié)點怎炊,從root.right
中重新尋找root
節(jié)點。同理廓译,當(dāng)root
的值>R
時评肆,需要從root.left
中重新尋找root
節(jié)點。當(dāng)L<=root.val<=R
時非区,則遞歸處理root
的左右子樹瓜挽。
python代碼
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def trimBST(self, root, L, R):
if root == None:
return None
if root.val < L:
return self.trimBST(root.right, L, R)
if root.val > R:
return self.trimBST(root.left, L, R)
root.left = self.trimBST(root.left, L, R)
root.right = self.trimBST(root.right, L, R)
return root
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(2)
assert Solution().trimBST(root, 3, 4) == None
root = TreeNode(3)
root.left = TreeNode(0)
root.right = TreeNode(4)
root.left.right = TreeNode(2)
root.left.right.left = TreeNode(1)
root = Solution().trimBST(root, 1, 3)
assert root.val == 3
assert root.left.val == 2
assert root.right == None
assert root.left.left.val == 1