您的位置:首页 > 其它

leetcode -- Path Sum

2013-08-10 23:38 281 查看
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.

public boolean hasPathSum(TreeNode root, int sum) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == null){
return false;
}

if(root.left == null && root.right == null && root.val == sum){
return true;
} else {
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}


/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null){
return false;
}
ArrayList<ArrayList<Integer>> result = pathSum(root, sum);
if(result.size() != 0){
return true;
}
return false;
}

public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> seqs = new ArrayList<Integer>();
int curSum = 0;

generatePathSum(root, result, seqs, curSum, sum);
return result;
}

public void generatePathSum(TreeNode root, ArrayList<ArrayList<Integer>> result,
ArrayList<Integer> seqs, int curSum, int expectedSum){
curSum += root.val;
seqs.add(root.val);

boolean isLeaf = root.left == null && root.right == null;
if(curSum == expectedSum && isLeaf){
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.addAll(seqs);
result.add(tmp);
}

if(root.left != null){
generatePathSum(root.left, result, seqs, curSum, expectedSum);
}

if(root.right != null){
generatePathSum(root.right, result, seqs, curSum, expectedSum);
}

seqs.remove(seqs.size() - 1);

}
}


public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null){
return false;
}
return checkPath(root, 0, sum);
}

public Boolean checkPath(TreeNode root, int curSum, int expectedSum) {
curSum += root.val;
boolean isLeaf = root.left == null && root.right == null;

if(curSum == expectedSum && isLeaf){
return true;
}
boolean lResult = false;
if(root.left != null){
lResult = checkPath(root.left, curSum, expectedSum);
}
boolean rResult = false;
if(root.right != null){
rResult = checkPath(root.right, curSum, expectedSum);
}

if(lResult || rResult){
return true;
}

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: