Leetcode 404(Java)

来源:互联网 发布:网络爬虫 编辑:程序博客网 时间:2024/05/21 19:26

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.

sum为所有左枝叶子结点的和,采用DFS递归调用SumOfLeftLeaves(),判断当前结点左子结点非空后,在判断其是否叶子结点,若是则将其值加入sum中,AC码如下:

public class Solution {    int sum=0;    public int sumOfLeftLeaves(TreeNode root) {        if(root==null)return 0;        if(root.left!=null){            if(root.left.left==null && root.left.right==null){                sum+=root.left.val;            }else{                sumOfLeftLeaves(root.left);            }        }        sumOfLeftLeaves(root.right);        return sum;    }}
0 0
原创粉丝点击