Given A binary search tree and the lowest and highest boundaries as L and R, trim the tree so it all it elements Li Es 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
The requirements described in this question are:
give us a binary sort tree minimum number L and max number R
What we need to do is crop the tree so that all the node values in the tree meet between L and R
thought:
Two fork sorting tree is characterized by: for any one node, the left subtree arbitrary node value is smaller than the node, right subtree arbitrary node value is larger than the root
so consider, for any one node,
If the value is smaller than L, then you should discard the root and go to the right subtree to find a new root.
if the value is larger than R, then you should discard the root and go to the left subtree to find a new root.
such an operation would be recursive.
My python code:
1 #Definition for a binary tree node.2 classTreeNode:3 def __init__(self, x):4Self.val =x5Self.left =None6Self.right =None7 8 classSolution:9 defTrimbst (self, root, L, R):Ten """ One : Type Root:treenode A : Type L:int - : Type R:int - : Rtype:treenode the """ - ifRoot isNone: - returnNone - ifRoot.val >R: + returnSelf.trimbst (Root.left, L,r) - ifroot.val<L: + returnSelf.trimbst (Root.right, L, R) ARoot.left =Self.trimbst (root.left,l,r) atRoot.right =Self.trimbst (root.right,l,r) - returnRoot - - - - if __name__=='__main__': ins =solution () - toroot = TreeNode (1) +Root.left =TreeNode (0) -Root.right = TreeNode (2) the * Print(Root.val,root.left.val,root.right.val) $ Panax NotoginsengRoot = S.trimbst (root,1,2) - the Print(Root, Root.left, root.right)
Leetcode algorithm: Trim a binar Search Tree