A non-recursive version


  • 0
    L

    Here is a non-recursive version based on inorder BST traversal:

        int sumOfLeftLeaves(TreeNode* root) {
            stack<TreeNode*> worklist;
            int sum = 0;
            bool isLeft = false;
            while(root || !worklist.empty()) {
                if(root) {
                    worklist.push(root);
                    root = root->left;
                    if(root) // set isLeft as true only when left child is NOT null
                        isLeft = true;
                } else {
                    root = worklist.top();
                    worklist.pop();
                    if(!root->right && isLeft) // find a left leaf
                        sum += root->val;
                    root = root->right;
                    isLeft = false; // set isLeft as false as now traverse along the right child
                }
            }
            return sum;
        }
    

Log in to reply
 

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