C++ non-recursive solution


  • 2
    Z
    class Solution {
    public:
        int sumOfLeftLeaves(TreeNode* root) {
            
            int res=0;
            stack<TreeNode*> s;
            
            if(!root) return 0;
            s.push(root);
            
            while(!s.empty()){
                TreeNode *current=s.top();
                s.pop();
                if(current->left){
                    if(!current->left->left && !current->left->right) res+=current->left->val;
                    else s.push(current->left);
                } 
                if(current->right){
                    if(current->right->left || current->right->right) s.push(current->right);
                }
            }
            
            return res;
        }
    };
    

Log in to reply
 

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