Python Simple Solution with explanation in comments


  • 0
    P
    def trimBST(self, root, L, R):
            """
            :type root: TreeNode
            :type L: int
            :type R: int
            :rtype: TreeNode
            """
            #base case : if root is null then return
            if not(root):
                return None
            
            #trim into simpler problems
            #if root value is lesser than L then left side of root doesn't matter
            if root.val<L:
                return self.trimBST(root.right,L,R)
            #if root value if higher than R then right side of root doesn't matter
            elif root.val>R:
                return self.trimBST(root.left,L,R)
            #else if it lies in the interval then decide for the left and right
            root.left=self.trimBST(root and root.left,L,R)
            root.right=self.trimBST(root and root.right,L,R)
            return root
    

Log in to reply
 

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