Python, Straightforward with Explanation

  • 2

    Let trim(node) be the answer for the subtree at that node.

    When node.val > R, we know the trimmed binary tree must occur to the left of the node. Similarly, when node.val < L, the trimmed binary tree occurs to the right of the node. Otherwise, we will trim both sides of the tree.

    def trimBST(self, root, L, R):
        def trim(node):
            if node:
                if node.val > R:
                    return trim(node.left)
                elif node.val < L:
                    return trim(node.right)
                    node.left = trim(node.left)
                    node.right = trim(node.right)
                    return node
        return trim(root)

Log in to reply

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