Question:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum
= 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
Code:
public static void sumAll(Node root, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> listAll) {
if (root == null) return;
list.add(root.v);
if (root.leftChild == null && root.rightChild == null) {
listAll.add(new ArrayList<Integer>(list));
}
sumAll(root.leftChild, list, listAll);
sumAll(root.rightChild, list, listAll);
list.remove(list.size() - 1);
}
class Node {
Node leftChild = null;
Node rightChild = null;
int v;
Node(int value) {
this.v = value;
}
}
本文介绍了一种算法,用于在给定的二叉树中找到所有从根节点到叶子节点的路径,使得这些路径的元素之和等于指定的数值。通过实例演示了如何实现这一算法。

被折叠的 条评论
为什么被折叠?



