题目描述:
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
思路:dfs的方法,每次选择左子或者右子,计算权重
定义一个二维数组res用来存放符合题目的路径
定义一个链表用于存放当前路径。
dfs函数:首先判断如果root为空,即到尾巴了,就直接return即可;
不然的话把root添加到path中,并且将exceptnumber-root.val
再判断如果root就是叶节点,并且exceptnumber=0说明是符合题意的路径,就把path加到res中。
递归进入左子树和右子树进行路径选择。
每次递归完以后,要把自己这个点从路径上删除
import java.util.ArrayList;
import java.util.LinkedList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer>> res=new ArrayList<>();
LinkedList<Integer> path=new LinkedList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
// 思路:递归寻找,分别递归左子树和右子树
dfs(root,expectNumber);
return res;
}
void dfs(TreeNode root,int expectNumber){
if(root==null) return;
path.add(root.val);
expectNumber-=root.val;
//到根节点,并且值到了要求的值
if(root.left==null&&root.right==null&&expectNumber==0){
res.add(new ArrayList<>(path));
}
// 左右子树递归
dfs(root.left,expectNumber);
dfs(root.right,expectNumber);
path.removeLast();
// 把这个路径在pop掉,移除最后一个元素
}
}