C++ 9-line very simplest recursion code


  • 0
    E

    Idea is simple and self-explanatory as given in the code comments.
    You can get the idea by taking simple examples of tree with 3 elements(or more).

    class Solution {
    public:
        TreeNode* trimBST(TreeNode* root, int L, int R) {
            if(root==NULL)
                return root;
    
            // if root is invalid
            if(root->val < L)
                return trimBST(root->right, L, R);
            if(root->val > R)
                return trimBST(root->left, L, R);
            
            // if root is valid
            root->left = trimBST(root->left, L, R);
            root->right = trimBST(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.