Very easy structured iterative solution!


  • 0
    X

    We only need to push the right branch into stack, so that we can make sure that every time we walk to an end is a left leave.
    var sumOfLeftLeaves = function(root) {
    var res = 0, stack = [];

    while(root || stack.length > 0) {
    if(root) {
    if(root.right) {
    stack.push(root.right);
    }
    if(root.left && !root.left.left && !root.left.right) {
    res += root.left.val;
    }
    root = root.left;
    } else {
    root = stack.pop();
    }
    }

    return res;
    };


  • 0
    X

    var sumOfLeftLeaves = function(root) {
    var res = 0, stack = [];

    while(root || stack.length > 0) {
    if(root) {
    if(root.right) {
    stack.push(root.right);
    }
    if(root.left && !root.left.left && !root.left.right) {
    res += root.left.val;
    }
    root = root.left;
    } else {
    root = stack.pop();
    }
    }

    return res;
    };


Log in to reply
 

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