[C++] 33ms lambda expression solution, thinking about how to simplify code


  • 0
    Z

    My solution use two stack<TreeNode*> to keep getting number in ascending and descending order. So that the time complex is O(n) and space complexity is O(h). Time looks good to me but takes too many lines to complete my logic.
    I'm new to lambda expression and wants to know if there is any way to make my code cleaner.

    bool findTarget(TreeNode* root, int k) {
        stack<TreeNode*> it;
        stack<TreeNode*> rit;
        // initialize its
        TreeNode* tmp = root, *rtmp = root;
        while(tmp != nullptr){
            it.push(tmp);
            tmp = tmp->left;
        }
        while(rtmp != nullptr){
            rit.push(rtmp);
            rtmp = rtmp->right;
        }
        
        function<int()> next = [&](){// set iterate function
            TreeNode* tnode = it.top();
            it.pop();
            if(tnode->right != nullptr){ 
                it.push(tnode->right);
                while( it.top()->left != nullptr){
                    it.push(it.top()->left);
                }
            }
            return tnode->val;
        };
        function<int()> rnext = [&](){// set iterate function
            TreeNode* tnode = rit.top();
            rit.pop();
            if(tnode->left != nullptr){ 
                rit.push(tnode->left);
                while( rit.top()->right != nullptr){
                    rit.push(rit.top()->right);
                }
            }
            return tnode->val;
        };
        int l = next(), r = rnext();
        while(l != r){
            if(l + r < k) l = next();
            else if(l + r > k) r = rnext();
            else return true;
        }
        return false;
    }

Log in to reply
 

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