0404. Sum of Left Leaves (E)

Sum of Left Leaves (E)

题目

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.

题意

求树中所有左叶结点的值之和。

思路

递归遍历判断是不是左叶结点即可。


代码实现

Java

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        return dfs(root, false);
    }

    private int dfs(TreeNode p, boolean left) {
        if (p == null) {
            return 0;
        }

        if (p.left == null && p.right == null) {
            return left ? p.val : 0;
        }

        return dfs(p.left, true) + dfs(p.right, false);
    }
}
原文地址:https://www.cnblogs.com/mapoos/p/13558025.html