第一题 判断是否存在这样的路径
题目链接:112. 路径总和
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
if (root.val == sum && root.left == null && root.right == null) {
return true;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
第二题 返回这样的路径List
参考:《剑指offer》系列 二叉树中和为某一值的路径(Java)
class Solution {
private List<List<Integer>> list = new ArrayList<>();
private LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null) {
return list;
}
help(root, sum);
return list;
}
public void help(TreeNode root, int sum) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null && root.val == sum) {
list.add(new LinkedList<>(path));
}
help(root.left, sum - root.val);
help(root.right, sum - root.val);
path.removeLast();
}
}
题目三 找出路径和等于给定数值的路径总数(不需要从根节点开始)
题目链接:437. 路径总和 III
class Solution {
public int pathSum(TreeNode root, int sum) {
if(root == null){
return 0;
}
return countPath(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
public int countPath(TreeNode root,int sum){
if(root == null){
return 0;
}
sum = sum - root.val;
int result = sum == 0 ? 1 : 0;
return result + countPath(root.left, sum) + countPath(root.right, sum);
}
}
题目四 最大路径和
题目链接:124. 二叉树中的最大路径和
class Solution {
int maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxGain(root);
return maxSum;
}
public int maxGain(TreeNode node) {
if (node == null) {
return 0;
}
// 递归计算左右子节点的最大贡献值
// 只有在最大贡献值大于 0 时,才会选取对应子节点
int leftGain = Math.max(maxGain(node.left), 0);
int rightGain = Math.max(maxGain(node.right), 0);
// 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
int priceNewpath = node.val + leftGain + rightGain;
// 更新答案
maxSum = Math.max(maxSum, priceNewpath);
// 返回节点的最大贡献值
return node.val + Math.max(leftGain, rightGain);
}
}