[LeetCode] Path Sum
2015-08-20 09:52
232 查看
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
这道题挺简单的,直接用recursive做就可以了。因为反正每一个node检查的方式都一样。
只要目前的sum减去正在检查的node的value之后等于0,就可以return true。
所以程序还是很简单的。
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.
这道题挺简单的,直接用recursive做就可以了。因为反正每一个node检查的方式都一样。
只要目前的sum减去正在检查的node的value之后等于0,就可以return true。
所以程序还是很简单的。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root==null){ return false; } sum=sum-root.val; if(root.left==null&&root.right==null){ if(sum==0){ return true; } return false; } return hasPathSum(root.left,sum)||hasPathSum(root.right,sum); } }
相关文章推荐
- 求排列组合
- 字符串处理
- C++ Primer 学习笔记(第三章:字符串、向量和数组)
- Java学习之路0715(二)(变量的使用、声明,赋值,运算符,控制语句)
- 无线局域网技术
- 三国关于诸葛亮的成语
- close_wait状态的产生原因及解决
- 程序猿,你调试过的最难 Bug 是?
- 一分钟让你会用反射
- 数组指针和指针数组
- 计算机系统:文章6章(存储器层次结构)
- System.Security.SecurityException The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception
- Java多线程--创建线程
- 移动端字体和字体大小规范
- 问题:webservice浏览后 无法输入参数;结果:调试Web Service时不能输入参数的解决办法
- 后台UI模板开发规范
- java读入txt时去除两端的空格
- [leetcode]Roman to Integer C语言
- Kth Smallest Element in a BST
- 雷军边吐槽边唱多:手游市场“还在山沟里”