1.本题知识点
二叉树,深度优先遍历,递归
2. 题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
3. 思路
① 使用深度优先搜索–先序遍历;
② 在遍历过程中,到达叶子节点时就是一条路径,此时判断该路径和是不是等于输入整数即可。举例,二叉树结构如下图,输入值为22:

遍历过程

我们发现,保存路径的数据结构实际上是一个栈。再贴个图说明下路径和保存它的数据结构的变化过程:

由于栈是后进先出的,编码的时候保存路径需要遍历栈,不如直接用ArrayList代替栈实现后进先出即可。
Java版本:
import java.util.ArrayList;
public class Solution {
private ArrayList<ArrayList<Integer>> result = new ArrayList<>();
private ArrayList<Integer> path = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null ) return result;
path.add(root.val);
boolean isLeaf = root.left == null && root.right == null;
if((target - root.val) == 0 && isLeaf){
result.add(new ArrayList<Integer>(path));
}
if(root.left != null) FindPath(root.left,target - root.val);
if(root.right != null) FindPath(root.right,target - root.val);
path.remove(path.size() - 1);
return result;
}
}