LeetCode|Path Sum-java
2015-09-26 16:27
471 查看
题目:
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
思路:
判断二叉树从根节点到所有叶子节点的和是否等于给的数值,如果是返回true,如果不是返回false,使用前序遍历的方式访问到某一节点时,累加该节点的值。如果该节点为叶节点并且路径中节点值的和搞好等于输入的整数,则当前的路径复合要求,返回true。
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.
思路:
判断二叉树从根节点到所有叶子节点的和是否等于给的数值,如果是返回true,如果不是返回false,使用前序遍历的方式访问到某一节点时,累加该节点的值。如果该节点为叶节点并且路径中节点值的和搞好等于输入的整数,则当前的路径复合要求,返回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 static boolean findPath(TreeNode pRoot, int expectSum , int currentSum) { currentSum += pRoot.val; boolean isLeaf = pRoot.left == null && pRoot.right == null; if (currentSum == expectSum && isLeaf) { return true; } if (pRoot.left != null && findPath(pRoot.left, expectSum, currentSum)) { return true; } if (pRoot.right != null && findPath(pRoot.right, expectSum, currentSum)) { return true; } return false; } public static boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } return findPath(root, sum, 0); } }
相关文章推荐
- java中static关键字的理解
- LeetCode|Pascal's Triangle-java
- struts1工作原理
- Java中finalize()用法
- java数组和向量
- Java之内存分析和String对象
- java中代理模式以及new和newInatance()的区别
- dos写helloworld程序总结 java 和 javac的使用
- JAVA 的普通加法运算
- Java Socket编程----通信是这样炼成的
- Java:instanceof用法
- java基础的一些概念.够自己有时间查看
- Java用ZIP进行多文件压缩保存
- Java的this关键字的使用与方法的重载相关知识
- Java用GZIP进行简单压缩
- test8.2
- 【Java基础第三弹】List集合的复制
- JAVA--读取csv文件并导数
- Java的访问修饰符与变量的作用域讲解
- Struts2标签-UI标签