404. Sum of Left Leaves
来源:互联网 发布:互联网灰色产业链知乎 编辑:程序博客网 时间:2024/05/01 00:47
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.
自己的方法稍微有一些naive,思路是一直找左节点,找到之后sum累加,但是root.left == null && root.right == null的判断方法会误判右子节点,不如用root.left.left == null && root.left.right == null,先记录自己的代码,代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int sumOfLeftLeaves(TreeNode root) { if (root == null || (root.left == null && root.right == null)) { return 0; } int[] sum = new int[1]; findleftleave(root, sum, 0); return sum[0]; } public int findleftleave(TreeNode root, int[] sum, int val) { if (root.left == null && root.right == null) { sum[0] = sum[0] + root.val; } if (root.left != null) { findleftleave(root.left, sum, root.val) ; } if (root.right != null && (root.right.left != null || root.right.right != null)) { findleftleave(root.right, sum, root.val); } return sum[0]; }}比较好的方法如下:
public class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root == null) return 0; int ans = 0; if(root.left != null) { if(root.left.left == null && root.left.right == null) ans += root.left.val; else ans += sumOfLeftLeaves(root.left); } ans += sumOfLeftLeaves(root.right); return ans; }}
0 0
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves*
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 将一个activity以对话框的形式悬浮在另一个activity之上
- mysql 整理之mysql sql语句相关
- Android注解框架(ButterKnife的简单使用)
- Dropbox是如何安全地存储用户帐号密码的?(2017-02-08 薛命灯)
- Java调用Python
- 404. Sum of Left Leaves
- Mac 搭建Android开发环境
- JVM运行数据环境
- Leetcode 198. House Robber
- jTable插件辅助资料
- mysql5.7.17安装(mysql-5.7.17-winx64.zip)
- 如何在eclipse里生成javadoc文档
- Spring MVC--2.@RequestMapping 映射请求
- WebStorm 注册码