您的位置:首页 > 编程语言 > Java开发

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
sum
= 22
,
5
/ \
4   8
/   / \
11  13  4
/  \      \
7    2      1


return true, as there exist a root-to-leaf path
5->4->11->2
which 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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: