【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】404 Sum of Left Leaves(java实现)
- LeetCode 404 Sum of Left Leaves (DFS)
- leetcode 404 Sum of Left Leaves C++
- Leetcode: Sum of Left Leaves
- [LeetCode-404]Sum of Left Leaves(java)
- leetcode-404-Sum of Left Leaves
- Leetcode #404 Sum of Left Leaves
- leetcode 404 Sum of Left Leaves
- leetcode 404 Sum of Left Leaves
- [LeetCode] Sum of Left Leaves 左子叶之和
- leetcode 404 Sum of Left Leaves
- LeetCode: Sum of Left Leaves
- LeetCode : Sum of Left Leaves
- LeetCode 404 Sum of Left Leaves
- leetcode_Sum of Left Leaves
- 【LeetCode】Sum of Left Leaves 左叶子之和
- LeetCode 404. Sum of Left Leaves 解题报告
- leetcode404: Sum of Left Leaves
- LeetCode 404:Sum of Left Leaves
- LEETCODE--Sum of Left Leaves