首页 > 其他 > 详细

0404. Sum of Left Leaves (E)

时间:2020-08-25 10:51:02      阅读:67      评论:0      收藏:0      [点我收藏+]

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);
    }
}

0404. Sum of Left Leaves (E)

原文:https://www.cnblogs.com/mapoos/p/13558025.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!