二叉树中和为某一值的路径_JAVA_较难
二叉树中和为某一值的路径
http://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
- 递归解决
import java.util.ArrayList; public class Solution { public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { ArrayList<ArrayList<Integer>> res = new ArrayList(); ArrayList<Integer> cache = new ArrayList(); FindPathRes(root, target, res, cache); return res; } public void FindPathRes(TreeNode root,int target,ArrayList<ArrayList<Integer>> res, ArrayList<Integer> cache) { if(root == null) { return; } cache.add(root.val); // 结果符合则输出 if(target == root.val && !cache.isEmpty() && root.left == null && root.right == null) { ArrayList<Integer> list = new ArrayList(); list.addAll(cache); res.add(list); } FindPathRes(root.left, target - root.val, res, cache); FindPathRes(root.right, target - root.val, res, cache); cache.remove(cache.size() - 1); } }