Implement a subtree function to cut the BST by the given range, inclusive, and then return the root of this subtree.
TreeNode subtree(TreeNode root, int min, int max )
@yubad2000 I am not sure about this. But I can propose you to write the company tag in the problem description. I suppose that later admins will move the problem in the appropriate discussion group.
@yubad2000 What will be the output of this example?Range is [37..55]. Do we need to trim all substrees out of range? Thank you
---------------50------
---------30---------80
-----------------54------
----------------------72
@elmirap said in BST subtree:
What will be the output of this example?Range is [37..55]. Thank you
---------------50------
---------30---------80
-----------------54------
----------------------72
The result should be also a BST, so could be:
50
\
54
or
54
/
50
def trimTree(root, min, max):
if root != None:
if root.val >= min and root.val <= max:
root.left = trimTree(root.left, min, max)
root.right = trimTree(root.right, min, max)
elif root.val > max:
return trimTree(root.left, min, max)
else:
return trimTree(root.right, min, max)
return root