LeetCode 112 Path Sum
题意:
给定一个二叉树和一个和,判断从树的根结点到叶子结点的所有结点的和是否等于给定的和,如果等于返回ture,否则false
思路:递归,遍历树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class LeetCode112 {
public boolean hasPathSum(TreeNode root, int sum) {
// boolean flag = false;
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);
}
}
LeetCode 113 Path Sum II
题意:
给定一棵二叉树和一个和,判断从树的根结点到叶子结点的所有结点的和是否等于给定的和,如果等于就记录这条路径。
解题思路:
对树进行遍历,并且使用回溯法进行求解。
public class Solution {
private List<List<Integer>> result;
private List<Integer> l;
private int sum;
private int curSum = 0;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
result = new LinkedList<>();
if (root == null) return result;
this.sum = sum;
l = new LinkedList<>(); //不能在pathSum(TreeNode root)中声明,在下面函数中是引用调用,每次都重新声明,必然错误
pathSum(root);
return result;
}
private void pathSum(TreeNode root) {
if (root != null) {
l.add(root.val);
curSum += root.val;
if(root.left == null && root.right == null && curSum == sum){
List<Integer> list = new LinkedList<>();
for(Integer i : l){
list.add(i);
}
result.add(list);
}
if(root.left != null){
pathSum(root.left);
}
if(root.right != null){
pathSum(root.right);
}
curSum -= root.val;
//删除最后一个,因为此条路不正确要回溯,如果不删除,则一直保留此节点,导致后面都不对
l.remove(l.size() - 1);
}
}
}
LeetCode 437. Path Sum III
题意:
给定一棵二叉树和一个和sum,求所有路径和为sum的个数,此路径不必从根结点开始。
public class LeetCode437 {
public int pathSum(TreeNode root, int sum) {
if(root == null)
return 0;
return pathNum(root,sum) + pathSum(root.left,sum) + pathSum(root.right,sum);
}
// 求从root开始的路径等于sum的个数
public int pathNum(TreeNode root, int sum) {
int res = 0;
if(root == null)
return res;
if(root.val == sum){
res++;
}
res = res + pathNum(root.left, sum - root.val) + pathNum(root.right, sum - root.val);
return res;
}
}