JAVA版本
一.路径总和:
本题的思路较为简单,只需要用target来减去值即可。
解法一:使用递归的方法
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null){
return false;
}
targetSum -= root.val;
if(root.left == null && root.right ==null) { //根节点,相当于中序
return targetSum ==0;
}
if (root.left != null){
boolean left = hasPathSum(root.left, targetSum);
if (left) { // 已经找到,注意加上判断。
return true;
}
}
if (root.right != null){
boolean right = hasPathSum(root.right, targetSum);
if (right) { // 已经找到
return true;
}
}
return false;
}
}
解法二:使用层序遍历,将父亲节点的值加到子节点当中去,然后使用层序遍历的方式,依次遍历结点,判断结点的值是否与target相同。
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
Stack <TreeNode> stack1 = new Stack<>();
Stack <Integer> stack2 = new Stack<>();
stack1.push(root);
stack2.push(root.val);
while(!stack1.isEmpty()) {
int size =stack1.size();
for (int i =0;i<size;i++){
TreeNode node = stack1.pop();
int sum = stack2.pop();
if (node.left ==null &&node.right ==null && sum == targetSum){
return true;
}
//使用的是栈,注意栈的入栈顺序
if (node.left != null) {
stack1.push(node.left);
stack2.push(sum + node.left.val);
}
if (node.right != null) {
stack1.push(node.right);
stack2.push(sum + node.right.val);
}
}
}
return false;
}
}
二.路径总和||:
本题使用了时间回溯的解法,因为要返回的是具体的路径。
本题与之前做的,求二叉树的所有路径相同。
本题的结束条件需要判断target与每一个值。
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res; // 非空判断
List<Integer> path = new ArrayList<>();//记录路径
preorderdfs(root, targetSum, res, path);
return res;
}
public void preorderdfs(TreeNode root, int targetsum, List<List<Integer>> res, List<Integer> path) {
path.add(root.val);
// 遇到了叶子节点
if (root.left == null && root.right == null) {
// 找到了和为 targetsum 的路径
if (targetsum - root.val == 0) {
res.add(new ArrayList<>(path));
}
return; // 如果和不为 targetsum,返回
}
if (root.left != null) {
preorderdfs(root.left, targetsum - root.val, res, path);
path.remove(path.size() - 1); // 回溯
}
if (root.right != null) {
preorderdfs(root.right, targetsum - root.val, res, path);
path.remove(path.size() - 1); // 回溯
}
}
}