Leetcode——二叉树中和为某一值的路径(路径总和 II)
Posted Yawn,
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode——二叉树中和为某一值的路径(路径总和 II)相关的知识,希望对你有一定的参考价值。
1. 题目
2. 题解
(1)DFS
- 深度优先遍历每一个路径,符合条件的存下来
/**
* Definition for a binary tree node.
* 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 {
//深度优先遍历(回溯)
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if(root == null)
return res;
dfs(new ArrayList<Integer>(), 0, root, targetSum);
return res;
}
public void dfs(ArrayList<Integer> curPath, int curSum, TreeNode node, int targetSum ){
//能进来肯定保证非空
curPath.add(node.val);
curSum+=node.val;
//判断符合条件的路径
if(node.left == null && node.right == null && curSum == targetSum){
res.add(new ArrayList<>(curPath));
}
if(node.left != null)
dfs(curPath,curSum,node.left,targetSum);
if(node.right != null)
dfs(curPath,curSum,node.right,targetSum);
curPath.remove(curPath.size()-1); //回溯,移除最后一位不符合条件的值
//curSum-=node.val; :不需要这句,每个节点都有针对他自己的curSum,不需要回溯
}
}
(2)BFS
/**
* Definition for a binary tree node.
* 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 {
List<List<Integer>> ret = new LinkedList<List<Integer>>();
Map<TreeNode, TreeNode> map = new HashMap<TreeNode, TreeNode>(); //保存,左子树跟右子树的根节点
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if (root == null) {
return ret;
}
Queue<TreeNode> queueNode = new LinkedList<TreeNode>();
Queue<Integer> queueSum = new LinkedList<Integer>(); //记录当前节点的和
queueNode.offer(root);
queueSum.offer(0);
while (!queueNode.isEmpty()) {
TreeNode node = queueNode.poll();
int rec = queueSum.poll() + node.val;
if (node.left == null && node.right == null) {
if (rec == targetSum) {
getPath(node);
}
} else {
if (node.left != null) {
map.put(node.left, node);
queueNode.offer(node.left);
queueSum.offer(rec);
}
if (node.right != null) {
map.put(node.right, node);
queueNode.offer(node.right);
queueSum.offer(rec);
}
}
}
return ret;
}
//根据Map存的父节点子,回溯找到路径,注意:此时找到路径是反的
public void getPath(TreeNode node) {
List<Integer> temp = new LinkedList<Integer>();
while (node != null) {
temp.add(node.val); //可以使用temp.add(0, node.val);
node = map.get(node);
}
Collections.reverse(temp); //注释掉这句即可
ret.add(new LinkedList<Integer>(temp));
}
}
以上是关于Leetcode——二叉树中和为某一值的路径(路径总和 II)的主要内容,如果未能解决你的问题,请参考以下文章
leetcode-剑指 Offer 34二叉树中和为某一值的路径
Leetcode——二叉树中和为某一值的路径(路径总和 II)
[LeetCode]剑指 Offer 34. 二叉树中和为某一值的路径