【LeetCode】Sum of Left Leaves 解题报告
来源:互联网 发布:先锋网络电视vip 编辑:程序博客网 时间:2024/05/16 16:03
【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 7There 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 日
0 0
- 【LeetCode】Sum of Left Leaves 解题报告
- LeetCode 404. Sum of Left Leaves 解题报告
- [leetcode] 404. Sum of Left Leaves 解题报告
- [Leetcode] 404. Sum of Left Leaves 解题报告
- Leetcode 404. Sum of Left Leaves 左叶子节点的和 解题报告
- Sum of Left Leaves ---LeetCode
- Leetcode Sum of Left Leaves
- LEETCODE--Sum of Left Leaves
- LeetCode : Sum of Left Leaves
- leetcode- Sum of Left Leaves
- LeetCode Sum of Left Leaves
- LeetCode笔记:404. Sum of Left Leaves
- 【leetcode】404. Sum of Left Leaves【E】
- LeetCode—404. Sum of Left Leaves
- [LeetCode]404. Sum of Left Leaves
- LeetCode 404 Sum of Left Leaves
- [LeetCode-404]Sum of Left Leaves(java)
- Leetcode 404. Sum of Left Leaves
- Spring IOC容器启动简介
- kafka实战案例分析总结
- Maven配置文件pom.xml详解
- Python3.52安装扩展错误
- struts2的执行流程(执行原理)
- 【LeetCode】Sum of Left Leaves 解题报告
- ArrayList,Vector, LinkedList的存储性能和特性
- tcpdump过滤特定IP的数据包,结果不对?
- 0107
- C语言register关键字
- JVM加载class文件的原理机制?
- NetBeans的代码度量插件SourceCodeMetrics的基本使用方法
- 修改百度输入法截图保存的默认文件名
- GC是什么? 为什么要有GC