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>(); } }
相关文章推荐
- Minimum Path Sum of a Binary Tree
- Sum of a tree
- Leetcode: mimimum depth of tree, path sum, path sum II
- geeksforgeeks Find the maximum path sum between two leaves of a binary tree
- Finding max & sum of a tree in Haskell with map
- leetcode -day17 Path Sum I II & Flatten Binary Tree to Linked List & Minimum Depth of Binary Tree
- LeetCode@Tree_404_Sum_of_Left_Leaves
- [124]. Binary Tree Maximum Path Sum, [543]. Diameter of Binary Tree
- Given a tree, find the node with the minimum sum of distances to other nodes
- LeetCode 111 Minimum Depth of Binary Tree
- Binary Tree Maximum Path Sum
- HDU - 3415 Max Sum of Max-K-sub-sequence
- 111 Minimum Depth of Binary Tree
- POJ 2739 Sum of Consecutive Prime Numbers(尺取法)
- leetcode-Binary Tree Maximum Path Sum
- [Lintcode]Maximum Depth of Binary Tree
- HDU 4432 Sum of divisors (进制转换模板)
- leetcode--minimum-depth-of-binary-tree
- UVa 1213 - Sum of Different Primes
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree