LC 0669 [M] Trim a Binary Search Tree - ALawliet/algorithms GitHub Wiki
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return None
if root.val > high: # we can throw out the entire right subtree
return self.trimBST(root.left, low, high)
if root.val < low: # we can throw out the entire left subtree
return self.trimBST(root.right, low, high)
# the subtree is in bounds but its subtrees may not be so we may have to trim and reassign
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root