Title Description
Given a binary search tree, while the given minimum and maximum boundary boundary L R. By pruning the binary search tree, so that the values of all the nodes in the [L, R] in the (R> = L). You may need to change the root of the tree, so the results should return good binary search tree pruning the new root node.
Algorithm thinking
Binary Tree Recursive natural fit.
First edition:
class Solution:
def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
if root==None:return None
# if root.val<L:root=root.right
# elif root.val>R:root=root.left
# if root==None:return None
# root.left=self.trimBST(root.left,L,R)
# root.right=self.trimBST(root.right,L,R)
# return root
The output is [3,2,4], the answer is [3, null, 4].
Clearly, where a node, root = root.right, then node 2 has not been directly verified
# root.left=self.trimBST(root.left,L,R)
# root.right=self.trimBST(root.right,L,R)
Then returned.
After the simple thought:
Second Edition:
class Solution:
def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
if root==None:return None
if root.val<L:root=self.trimBST(root.right,L,R)
elif root.val>R:root=self.trimBST(root.left,L,R)
else:
root.left=self.trimBST(root.left,L,R)
root.right=self.trimBST(root.right,L,R)
return root
When execution: 52 ms, beat the 85.43% of users in all Python3 submission