[LeetCode]Path Sum
2016-02-17 16:10
274 查看
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and
return true, as there exist a root-to-leaf path
题挺水的,不过刚开始一直wa了几次,发觉基础真的好重要,我把leaf这个概念弄混了.我刚开始只是判断有一条路某时刻满足条件就判断true了,结果就wa了好几次.
leaf的定义是左右子节点都为空!!!
code
For example:
Given the below binary tree and
sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path
5->4->11->2which sum is 22.
题挺水的,不过刚开始一直wa了几次,发觉基础真的好重要,我把leaf这个概念弄混了.我刚开始只是判断有一条路某时刻满足条件就判断true了,结果就wa了好几次.
leaf的定义是左右子节点都为空!!!
code
public class Solution { public boolean hasPathSum( TreeNode root, int sum ) { if( root != null ) { sum -= root.val; if( sum == 0 && root.left == null && root.right == null ) return true; else return hasPathSum( root.left, sum ) || hasPathSum( root.right, sum ); } else return false; } public static void main( String[] args ) { Solution s = new Solution(); TreeNode root = new TreeNode( 5 ); root.left = new TreeNode( 4 ); root.left.left = new TreeNode( 11 ); root.left.left.left = new TreeNode( 7 ); root.left.left.right = new TreeNode( 2 ); root.right = new TreeNode( 8 ); root.right.left = new TreeNode( 13 ); root.right.right = new TreeNode( 4 ); root.right.right.right = new TreeNode( 1 ); // root.left = new TreeNode( 1 ); System.out.println( s.hasPathSum( root, 9 ) ); } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode( int x ) { val = x; } }
相关文章推荐
- 美食 - 菜
- 《转》__block修饰符
- 有关HTML的相关基础问题:
- 伪元素
- CocoaPods 安装
- 半壶纱-刘珂矣
- 不错的Spring学习笔记(转)
- 亿级商品详情页架构演进技术解密
- switf类型别名
- [ASP.NET MVC] ASP.NET Identity登入技术应用
- BZOJ_P2705 [SDOI2012]Longge的问题(数论+欧拉函数)
- 关于vmware11下安装centOS6.5出现eth0 no link present问题解决方法
- 指定linux软件安装路径
- java术语(PO/POJO/VO/BO/DAO/DTO)
- Tomcat性能调整完整教程
- EasyX简易绘图实例
- HTTP和HTTPS的区别
- 构造方向可控金字塔
- 服务器端架构,前端服务器与客户端随机负载平衡
- lazyLoad懒加载技术