标签:path rem root public bin 自己的 java array add
Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ 4 8
/ / 11 13 4
/ \ / 7 2 5 1
Return:
[ [5,4,11,2], [5,8,4,5] ]
题目大意:
找出从根节点到叶子节点路径上和为给定sum的路径。
解法:
先开始是用dfs做的,后来发现自己的dfs会将一个路径添加两次。因为在递归到叶子节点的左右都是为空的,这时就会在res数组中添加两次。
java:
class Solution {
private void dfs(List<List<Integer>>res,List<Integer>tmp,TreeNode node,int tmpSum){
if(node==null){
if(tmpSum==0) {
res.add(new ArrayList<>(tmp));
}
return;
}
if(tmpSum<0) return;
tmp.add(node.val);
dfs(res,tmp,node.left,tmpSum-node.val);
dfs(res,tmp,node.right,tmpSum-node.val);
tmp.remove(tmp.size()-1);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>>res=new ArrayList<>();
List<Integer>tmp=new ArrayList<>();
dfs(res,tmp,root,sum);
return res;
}
}
改了之后递归结束的条件就是节点的左右子节点都为空,则当前节点就是叶子节点。
java:
class Solution {
private void dfs(List<List<Integer>>res,List<Integer>tmp,TreeNode node,int tmpSum){
if(node.left==null&&node.right==null){
if(tmpSum==0) {
res.add(new ArrayList<>(tmp));
}
return;
}
if(node.left!=null) {
tmp.add(node.left.val);
dfs(res, tmp, node.left, tmpSum - node.left.val);
tmp.remove(tmp.size() - 1);
}
if(node.right!=null) {
tmp.add(node.right.val);
dfs(res, tmp, node.right, tmpSum - node.right.val);
tmp.remove(tmp.size() - 1);
}
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>>res=new ArrayList<>();
if(root==null) return res;
List<Integer>tmp=new ArrayList<>();
tmp.add(root.val);
dfs(res,tmp,root,sum-root.val);
return res;
}
}
标签:path rem root public bin 自己的 java array add
原文地址:https://www.cnblogs.com/xiaobaituyun/p/10705241.html