- 路径总和 II
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
示例 2:
输入:root = [1,2,3], targetSum = 5
输出:[]
示例 3:
输入:root = [1,2], targetSum = 0
输出:[]
public class test113
{ List<List<Integer>>ans=new LinkedList<>();
LinkedList<Integer>temp=new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
//深度优先遍历
dfs(root,targetSum);
return ans;
}
public void dfs(TreeNode root, int targetSum)
{ //
if(root==null)
return;
//增加当前值到路径中
temp.add(root.val);
//表示已经遍历到了根节点
if(root.left==null&&root.right==null)
//这里特别注意,判定出相等,应当放入到最终结果中时候,需要使用new LinkedList<>(temp)。放入一个新建的对象,不然实时更新,会出错
if(summ(temp)==targetSum)
ans.add(new LinkedList<>(temp));
dfs(root.left,targetSum);
dfs(root.right,targetSum);
//temp.remove(temp.size()-1);
temp.removeLast();
}
public int summ(LinkedList<Integer>temp)
{
int sum=0;
for(int i=0;i<temp.size();i++)
{
sum=sum+temp.get(i);
}
return sum;
}
@Test
public void test()
{
TreeNode t1=new TreeNode(1);
TreeNode t2=new TreeNode(2);
TreeNode t3=new TreeNode(3);
TreeNode t4=new TreeNode(4);
t1.left=t2;
t1.right=null;
t2.left=t3;
t2.right=null;
t3.left=t4;
t3.right=null;
t4.left=null;
t4.right=null;
pathSum(t1,10);
System.out.println(ans);
//System.out.println("hello");
}
}
可以记录当前的值,但是回滚时候,需要将总和也减去当前值,从而可以少每次判定都计算总和的值.摘自:https://leetcode-cn.com/problems/path-sum-ii/solution/lu-jing-zong-he-iijava-by-sui-ji-guo-che-hrzg/
/**
* 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 {
int target = 0;
int curSum = 0;
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
this.target = targetSum;
if (root == null) {
return res;
}
traverse(root);
return res;
}
public void traverse(TreeNode root) {
if (root == null) {
return;
}
// 前序遍历位置
path.addLast(root.val);
curSum += root.val;
if (root.left == null && root.right == null) {
if (curSum == target) {
res.add(new LinkedList<>(path));
}
}
traverse(root.left);
traverse(root.right);
// 后序遍历位置
curSum -= root.val;
path.removeLast();
}
}
作者:sui-ji-guo-cheng-sui-ji-guo
链接:https://leetcode-cn.com/problems/path-sum-ii/solution/lu-jing-zong-he-iijava-by-sui-ji-guo-che-hrzg/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。