404. Sum of Left Leaves

404. Sum of Left Leavesarrow-up-right

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

My Solutions:

左叶节点的定义是本身是叶(不是root,且左右孩子为null),且是左节点。因此,只有满足这两个条件的节点值才会返回。

方法1:dfs recursive

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        return dfs(root, false);
    }
    
    public int dfs(TreeNode root, boolean isLeft){
        if (root.left == null && root.right == null && isLeft) return root.val;
        else {
            int lsum = 0, rsum = 0;
            if (root.left != null) lsum = dfs(root.left, true);
            if (root.right != null) rsum = dfs(root.right, false);
            return lsum + rsum;
       }
    }
}

方法2:dfs iterative。dfs一律用stack做,因为最后进的最先出,所以只要node.left != null,就一直压栈

方法3:bfs iterative。bfs一律用queue做,因为先进先出,所以总是loop完一层,再进入下一层

Last updated