112.路径总和
一、题目描述
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。
示例: 给定如下二叉树,以及目标和 sum = 22,
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
提示:
- 树中节点的数目在范围 [0, 5000] 内
- -1000 <= Node.val <= 1000
- -1000 <= targetSum <= 1000
二、解题思路
直接遍历从根节点到叶子节点的的路径看看总和是不是目标和。
递归法
深度遍历二叉树。
三、AC代码
递归法
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return root.val == targetSum;
}
return hasPathSum(root.left, targetSum-root.val) || hasPathSum(root.right, targetSum-root.val);
}
}
113.路径总和-ii
一、题目描述
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
示例: 给定如下二叉树,以及目标和 sum = 22,
提示:
- 树中节点的数目在范围 [0, 5000] 内
- -1000 <= Node.val <= 1000
- -1000 <= targetSum <= 1000
二、解题思路
跟 112.路径总和 相比,区别在这题要求返回所有符合条件的路径。
回溯法
深度遍历二叉树,用一个List集合专门来存储路径,再进行回溯就可以了。
三、AC代码
回溯法
class Solution {
LinkedList<Integer> path;
List<List<Integer>> result;
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
path = new LinkedList<>();
result = new ArrayList<>();
if (root == null) {
return result;
}
order(root, targetSum);
return result;
}
void order(TreeNode root, int targetSum) {
path.add(root.val);
if (root.left == null && root.right == null && targetSum == root.val) {
result.add(new ArrayList(path));
return ;
}
if (root.left != null) {
order(root.left, targetSum-root.val);
path.removeLast();
}
if (root.right != null) {
order(root.right, targetSum-root.val);
path.removeLast();
}
}
}
参考代码随想录:https://programmercarl.com/