---
# System prepended metadata

title: \#404 Sum of Left Leaves
tags: [binary tree, leetcode, leetcode-easy]

---

# \#404 Sum of Left Leaves
## *給定一二元樹, 回傳所有左節點的加總*
## Log
 - build 20210801 by syhuang

## 遞迴
 - 時間/空間複雜度都較遍歷方法高
 - leetcode submit runtime 10%, memory 40%
```javascript=
var sumOfLeftLeaves = function(root) {
    if(!root) return 0;
    let result = 0;
    if(root.left){
        if(!root.left.left && !root.left.right) result += root.left.val;
        result += sumOfLeftLeaves(root.left);
    }
    result += sumOfLeftLeaves(root.right);
    return result;
};
```
## 初見(遍歷)
 - 搭配[#144](articles/Leetcode/easy/144.md)遍歷二元樹，加上判斷當前節點是否為左節點(left leaf)就可以把node.val作加總
 - leetcode submit runtime 40%, memory 70%
```javascript=
var sumOfLeftLeaves = function(root) {
    let t = [];//暫存node
    let leftValSum = 0;
    let p = root;
    while(p || t.length>0){
        while(p){
            t.push(p);
            p = p.left;
            if(p && !p.left && !p.right) leftValSum += p.val;//左節點已經是根節點才作加總
        }
        p = t.pop();
        p = p.right;        
    }
    return leftValSum;
    
};
```
## 備註
## 參考
- [參考解](https://leetcode.com/problems/sum-of-left-leaves/discuss/88950/Java-iterative-and-recursive-solutions)
###### tags: `leetcode`, `leetcode-easy`, `binary tree`