题解 | #二叉树中和为某一值的路径#
二叉树中和为某一值的路径
http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
二叉树中的回溯
上来就回溯,别问为什么,综合评分也还凑合,贴一下吧
运行时间:16ms
超过80.33% 用Java提交的代码
占用内存:9736KB
超过73.69%用Java提交的代码
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); ArrayList<Integer> path = new ArrayList<>(); if (root == null) return res; findPathBackTrace(root, target, res, path); return res; } public void findPathBackTrace(TreeNode node, int remains, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> path) { if (node == null) return; if (node.left == null && node.right == null) { if (remains == node.val) { path.add(node.val); res.add(new ArrayList<>(path)); path.remove(path.size() - 1); } return; } else if (remains < node.val) { return; } path.add(node.val); findPathBackTrace(node.left, remains - node.val, res, path); findPathBackTrace(node.right, remains - node.val, res, path); path.remove(path.size() - 1); }