语言:Java
算法:递归
数据结构:栈
import java.util.ArrayList; import java.util.Stack; public class T23_FindPath { private ArrayList<ArrayList<Integer>> paths = new ArrayList<>(); private Stack<Integer> path = new Stack(); public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) { // 递归终止条件 if(root == null) return paths; path.push(root.val); target -= root.val; // 当前路径遍历结束时若节点值之和等于Target,则将该路径加入正确路径队列; if(target == 0 && root.left == null && root.right == null) paths.add(new ArrayList<Integer>(path)); FindPath(root.left, target); FindPath(root.right, target); // 当前节点判断结束,回溯; path.pop(); return paths; } }