Python solution, easy to understand

  • 0

    The trick here is if the root is not in the range, then either left child or right right is in the range (not both), or both of them are not in the range.

    class Solution:
        def trimBST(self, root, L, R):
            :type root: TreeNode
            :type L: int
            :type R: int
            :rtype: TreeNode
            if not root:
                return None
            left = self.trimBST(root.left, L, R)
            right = self.trimBST(root.right, L, R)
            if root.val >= L and root.val <= R:
                root.left = left
                root.right = right
                if left:
                    root = left
                    root = right
            return root

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.