码迷,mamicode.com
首页 > 其他好文 > 详细

计算二叉树每层的和

时间:2015-09-01 12:19:57      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

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());
    }

 

计算二叉树每层的和

标签:

原文地址:http://www.cnblogs.com/23lalala/p/4775191.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!