Java [Leetcode 112]Path Sum
2016-01-27 21:32
549 查看
题目描述:
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
解题思路:
递归法。
代码描述:
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
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.
解题思路:
递归法。
代码描述:
/** * 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; if(root.left == null && root.right == null && root.val == sum) return true; return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }
相关文章推荐
- JDK5.0中JVM堆模型、GC垃圾收集详细解析
- javaweb学习总结(十五)——JSP基础语法
- JavaWeb学习总结(十三)——使用Session防止表单重复提交
- JavaSE入门学习13:Java面向对象之封装
- java线程池问题
- struts2的struts.xml常量配置
- struts2的通配符用法
- Selenium2(java)selenium常用API 六
- Spring MVC一些知识
- Selenium2(java)selenium常用API 五
- java系列--JSON数据的处理
- Java正则表达式
- Java [Leetcode 119]Pascal's Triangle II
- Ubuntu12.04如何安装JDK
- springMVC在JSP页面取map值
- java中传值及引伸深度克隆的思考(说白了Java只能传递对象指针)
- ubuntu14.04 64位JDK安装
- win7 32位设置JDK1.6环境变量的方法
- Java 内存分配全面浅析
- javaweb第一弹--Servlet