题目: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.
源代码:
import java.util.Stack;
public class PathSum {
boolean result;
public boolean hasPathSum(TreeNode root, int sum){
if(root == null){
return false;
}else{
int curSum = 0;
Stack<Integer> path = new Stack<Integer>();
// boolean result = false;
findPathSum(root, path, curSum, sum);
return result;
}
}
private void findPathSum(TreeNode root, Stack<Integer> path, int curSum, int sum){
if(result){
return;
}
curSum += root.val;
boolean isLeaf = root.left == null && root.right == null;
path.push(root.val);
if(curSum == sum && isLeaf){
this.result = true;
return;
}
if(root.left != null){
findPathSum(root.left, path, curSum, sum);
}
if(root.right != null){
findPathSum(root.right, path, curSum, sum);
}
path.pop();
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
int sum = 1;
PathSum ps = new PathSum();
System.out.println(ps.hasPathSum(root, sum));
}
}
可能代码中还有一些不成熟的地方,请观者不吝指教,谢谢。
Path Sum II : Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
源代码:
public class PathSumII {
public static List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null){
return result;
}
int curSum = 0;
List<Integer> path = new ArrayList<Integer>();
pathSum(root, result, path, curSum, sum);
return result;
}
private static void pathSum(TreeNode root, List<List<Integer>> result,
List<Integer> path, int curSum, int sum) {
curSum += root.val;
path.add(root.val);
boolean isLeaf = root.left == null && root.right == null;
if(sum == curSum && isLeaf){
List<Integer> tmp = new ArrayList<Integer>();
for(int x : path){
tmp.add(x);
}
result.add(tmp);
}
if(root.left != null){
pathSum(root.left, result,path, curSum, sum);
}
if(root.right != null){
pathSum(root.right, result, path, curSum, sum);
}
path.remove(path.size() - 1);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
System.out.println(PathSumII.pathSum(root, 1));
}
}