c++ 13ms (not recursive)


  • 0
    X
    class Solution {
    public:
        TreeNode* trimBST(TreeNode* root, int L, int R) {
            
           // find the proper root
            while(root->val<L || root->val>R)
            {
                if(root->val<L) { root = root->right; }
                else { root = root->left; }
            }
            
            // temporary pointer for left and right subtree
            TreeNode *Ltemp = root;
            TreeNode *Rtemp = root;
            
            // remove the elements larger than L
            while(Ltemp->left)
            {
                if( (Ltemp->left->val)<L ) { Ltemp->left = Ltemp->left->right; }
                else { Ltemp = Ltemp->left; }
            }
             // remove the elements larger than R
            while(Rtemp->right)
            {
                if( (Rtemp->right->val)>R) { Rtemp->right = Rtemp->right->left; }
                else { Rtemp = Rtemp->right; }
            }
    
            return root;
        }
    };
    

Log in to reply
 

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