您的位置:首页 > 其它

【LeetCode】Sum of Left Leaves 解题报告

2017-01-07 22:08 591 查看

【LeetCode】Sum of Left Leaves 解题报告

标签(空格分隔): LeetCode

[LeetCode]

https://leetcode.com/problems/sum-of-left-leaves/

Difficulty: Easy

Question

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.


Ways

这个方法很直白很简单,用递归判断是不是左叶子,然后求和即可。我的第一次A过的代码是这样的。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
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;//加上左叶子的值
}
sumOfLeftLeaves(root.left);//循环左叶子
}
if(root.right!=null){
sumOfLeftLeaves(root.right);//循环右叶子
}

return sum;
}
}


AC:8 ms

看了高票解答之后,感觉自己还可以精简下代码。如下。

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

sum += sumOfLeftLeaves(root.right);

return sum;
}
}


AC:9 ms

Date

2017 年 1 月 7 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode