c++ & 4 lines python solutions


  • 0
    Z

    c++

    class Solution {
    public:
        TreeNode* trimBST(TreeNode* root, int L, int R) {
            if ( root ) {
                if ( root->val < L )
                    return trimBST(root->right, L, R);
                if ( root->val > R )
                    return trimBST(root->left, L, R);
                root->left = trimBST(root->left, L, R);
                root->right = trimBST(root->right, L, R);
            }
            return root;
        }
    };
    
    // 77 / 77 test cases passed.
    // Status: Accepted
    // Runtime: 23 ms
    

    python

    class Solution(object):
        def trimBST(self, root, L, R):
            """
            :type root: TreeNode
            :type L: int
            :type R: int
            :rtype: TreeNode
            """
            if root:
                if root.val < L:
                    return self.trimBST(root.right, L, R)
                if root.val > R:
                    return self.trimBST(root.left, L, R)
                root.left = self.trimBST(root.left, L, R)
                root.right = self.trimBST(root.right, L, R)
                return root
    
    # 77 / 77 test cases passed.
    # Status: Accepted
    # Runtime: 72 ms
    

    a compressed but a bit slower version can be

    class Solution(object):
        def trimBST(self, root, L, R):
            """
            :type root: TreeNode
            :type L: int
            :type R: int
            :rtype: TreeNode
            """
            if root:
                root.left = self.trimBST(root.left, L, R)
                root.right = self.trimBST(root.right, L, R)
                return root.right if root.val < L else root.left if root.val > R else root
    
    # 77 / 77 test cases passed.
    # Status: Accepted
    # Runtime: 106 ms
    

Log in to reply
 

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