You are given a tree, and the nodes in the tree may have more than two child nodes, calculate the sum of the tree where the root to the leaf is considered as a number.
public class TreeSum {
private static int sum = 0;
public void sumAll(Node root, ArrayList<Integer> list) {
if (root == null) return;
list.add(root.v);
if (root.children.size() == 0) {
sum += getValue(list);
}
for (Node n : root.children) {
sumAll(n, list);
}
list.remove(list.size() - 1);
}
public int getValue(ArrayList<Integer> list) {
if (list.size() == 0) return 0;
int value = 0;
for (int i = 0; i < list.size(); i++) {
value = 10 * value + list.get(i);
}
return value;
}
}
class Node {
ArrayList<Node> children;
int v;
Node(int v) {
this.v = v;
children = new ArrayList<Node>();
}
}