Trim a Binary Search Tree

Problem Id: 669 Difficulty: Medium Tag: Tree


Intuition

The trim means for each node who is greater than the limitation, we return its left sub-tree. For each node who is less than the limitation, we return its right sub-tree. So we could solve this problem recursivly.

Solution


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
        if root is None:
            return None
        if L <= root.val <= R:
            root.left = self.trimBST(root.left, L, R)
            root.right = self.trimBST(root.right, L, R)
            return root
        elif root.val > R:
            return self.trimBST(root.left, L, R)
        else:
            return self.trimBST(root.right, L, R)