zoukankan      html  css  js  c++  java
  • 计算二叉树每层的和

    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());
        }
  • 相关阅读:
    【转载】C/C++中extern关键字详解
    【转载】extern "C"的用法解析(原博主就是抄百度百科的,不如另外一篇好)
    lua Date和Time
    MySQL-Linux安装
    Hive-0.13安装
    MR案例:单表关联查询
    MR案例:小文件处理方案
    MR案例:链式ChainMapper
    MR案例:定制Partitioner
    MR案例:多文件输出MultipleOutputs
  • 原文地址:https://www.cnblogs.com/23lalala/p/4775191.html
Copyright © 2011-2022 走看看