BST is given.
Calculate and return array with a sum of every level.
For example,
1
2 3
4 5 1 2
Output should be [1, 5, 12].
遍历的时候记录节点在哪一层就行了,可以深度优先,不一定非得层序遍历。开始想复杂了
private static class BinaryNode { BinaryNode left; BinaryNode right; int val; private BinaryNode(BinaryNode left, BinaryNode right, int val) { this.left = left; this.right = right; this.val = val; } } private static void levelSum(BinaryNode root, Map<Integer, Integer> result, int level) { if (root == null) { return; } int levelSum; if (result.containsKey(level)) { levelSum = result.get(level); } else { levelSum = 0; } levelSum += root.val; result.put(level, levelSum); levelSum(root.left, result, level + 1); levelSum(root.right, result, level + 1); } public static void main(String args[]) { BinaryNode level2Left1 = new BinaryNode(null, null, 4); BinaryNode level2Right1 = new BinaryNode(null, null, 5); BinaryNode level1Left = new BinaryNode(level2Left1, level2Right1, 2); BinaryNode level2Left2 = new BinaryNode(null, null, 1); BinaryNode level2Right2 = new BinaryNode(null, null, 2); BinaryNode level1Right = new BinaryNode(level2Left2, level2Right2, 3); BinaryNode root = new BinaryNode(level1Left, level1Right, 1); Map<Integer, Integer> result = new HashMap<Integer, Integer>(); levelSum(root, result, 0); System.out.println(result.values()); }