index
title: 二叉树中和为某一值的路径 date: 2019-08-21T11:00:41+08:00 draft: false categories: offer
题目
解题思路
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
FindPath(res, new LinkedList<>(), root, 0, target);
res.sort(Comparator.comparingInt(list -> -list.size()));
return res;
}
private void FindPath(ArrayList<ArrayList<Integer>> res,
LinkedList<Integer> path,
TreeNode node,
int pathSum,
int target) {
if (node == null) {
return;
}
if (pathSum > target) {
return;
}
if (pathSum + node.val == target && node.right == null && node.left == null) {
ArrayList<Integer> resPath = new ArrayList<>(path);
resPath.add(node.val);
res.add(resPath);
return;
}
path.addLast(node.val);
if (node.left != null) {
FindPath(res, path, node.left, pathSum + node.val, target);
}
if (node.right != null) {
FindPath(res, path, node.right, pathSum + node.val, target);
}
path.removeLast();
}Last updated