路径总和 Ⅱ Java

java 复制代码
public class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;

	TreeNode() {
	}

	TreeNode(int val) {
		this.val = val;
	}

	TreeNode(int val, TreeNode left, TreeNode right) {
		this.val = val;
		this.left = left;
		this.right = right;
	}
}

class Solution {
	public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> list = new ArrayList();
        List<Integer> tempList = new ArrayList(); // 存放符合条件的节点
        dfs(list, tempList, root, targetSum);
        return list;
	}
    static void dfs(List<List<Integer>> list, List<Integer> tempList, TreeNode root, int targetSum) {
        if (root == null) return;
        targetSum -= root.val; // 减去该节点
        tempList.add(root.val); // 将当前节点加入tempList 
        if (root.left == null && root.right == null && targetSum == 0) list.add(new ArrayList(tempList)); // 判断是否为叶子节点,如果累积减去的值等于目标值则将tempList创建副本添加到list,一定要创建副本再存入防止tempList改变影响到list
        dfs(list, tempList, root.left, targetSum);
        dfs(list, tempList, root.right, targetSum);
        tempList.remove(tempList.size() - 1); // 回溯重置状态,撤回当前节点的存入
    }
}

或者用队列:

java 复制代码
class Solution {
	public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> list = new ArrayList();
        Deque<Integer> tempList = new LinkedList();
        dfs(list, tempList, root, targetSum);
        return list;
	}
    static void dfs(List<List<Integer>> list, Deque<Integer> tempList, TreeNode root, int targetSum) {
        if (root == null) return;
        targetSum -= root.val;
        tempList.offerLast(root.val); // 当前节点添加到队尾
        if (root.left == null && root.right == null && targetSum == 0) list.add(new LinkedList(tempList));
        dfs(list, tempList, root.left, targetSum);
        dfs(list, tempList, root.right, targetSum);
        tempList.pollLast(); // 回溯重置,移除队尾节点
    }
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

相关推荐
sunshine6412 分钟前
JS实现悬浮可拖拽vue组件封装
开发语言·前端·javascript
曹牧2 分钟前
C#中的StartsWith
java·服务器·c#
薛定谔的猫198211 分钟前
docker 安装redis
java·spring·mybatis
v***446711 分钟前
PLC(电力载波通信)网络机制介绍
开发语言·网络·php
q***428214 分钟前
解决bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException
java·数据库·sql
q***D44314 分钟前
【springboot】Spring 官方抛弃了 Java 8!新idea如何创建java8项目
java·spring boot·spring
s***558117 分钟前
SpringBoot整合JWT
java·spring boot·后端
p***924818 分钟前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat
K***728418 分钟前
将 vue3 项目打包后部署在 springboot 项目运行
java·spring boot·后端