二叉树中和为某一值的路径 发表于 2018-10-03 | 分类于 数据结构与算法 , 题目汇总 题目描述输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 123456789101112131415161718192021222324252627282930313233343536373839404142434445import java.util.ArrayList;import java.util.Stack;public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}public class Solution { public ArrayList<ArrayList<Integer>> findPath(TreeNode root,int target){ ArrayList<ArrayList<Integer>> pathList = new ArrayList<ArrayList<Integer>>(); if(root == null){ return pathList; } Stack<Integer> stack = new Stack<Integer>(); findPath(root, target, stack, pathList); return pathList; } private void findPath(TreeNode root, int target, Stack<Integer> path, ArrayList<ArrayList<Integer>> pathList) { if(root == null) return; if(root.left == null && root.right == null){ if(root.val == target){ ArrayList<Integer> ValList = new ArrayList<Integer>(); for(int i : path){ ValList.add(i); } ValList.add(root.val); pathList.add(ValList); } } else { path.push(new Integer(root.val)); findPath(root.left, target-root.val, path, pathList); findPath(root.right, target-root.val, path, pathList); path.pop(); } }}