Python Solution


  • 0
    K

    Personally found it easier to grasp without using 2 sets of recursions. Goes all the way down and trims when it goes up.

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

  • 0
    M

    @kew060 said in Python Solution:

    root.val <= R and root.val >= L

    Meh, rather ugly. Why not chain them?

    And I'd use else instead of the second elif. Because elif makes it looks like it's possible that root.val < L gets evaluated to False, which is misleading.


Log in to reply
 

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