给定二叉树和一个常数sum,求是否存在从根节点到叶子节点的路径,该路径上的所有节点值之和等于sum。
方法一:使用深度优先搜索,把已经遍历过的节点之和作为参数往下传递
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)
return false;
List<Integer> sumList = new LinkedList<Integer>();
getSumList(root, sumList, 0);
for(int i = 0; i < sumList.size(); i++){
if(sumList.get(i) == sum)
return true;
}
return false;
}
public void getSumList(TreeNode root, List<Integer> sumList, int sum){
if(root.left == null && root.right == null){
sumList.add(root.val + sum);
return;
}
if(root.left != null){
getSumList(root.left, sumList, sum + root.val);
}
if(root.right != null){
getSumList(root.right, sumList, sum + root.val);
}
}
方法二:递归相减
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(root.left == null && root.right == null && sum - root.val == 0) return true;
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
也可以不使用递归,而使用栈的方法