您的位置:首页 > 其它

Sum of a tree

2013-02-24 12:54 99 查看
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>();
}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: