Skip to main content

669. Trim a Binary Search Tree

https://leetcode.com/problems/trim-a-binary-search-tree/

Python

class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
return self.trim(root, low, high)

def trim(self, node, low, high):
if not node:
return

if node.val > high:
return self.trim(node.left, low, high)
elif node.val < low:
return self.trim(node.right, low, high)
else:
node.left = self.trim(node.left, low, high)
node.right = self.trim(node.right, low, high)
return node