首页 > 其他 > 详细

1161. Maximum Level Sum of a Binary Tree

时间:2019-09-27 10:10:49      阅读:122      评论:0      收藏:0      [点我收藏+]
import java.util.*
import kotlin.collections.HashMap

/**
 * 1161. Maximum Level Sum of a Binary Tree
 * https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/
 * */
class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

class Solution {
    fun maxLevelSum(root: TreeNode?): Int {
        var level = 0
        var max = 0
        val map = HashMap<Int, Int>()
        val stack = Stack<TreeNode>()
        stack.add(root)
        while (!stack.isEmpty()) {
            level++
            var oneLevelSum = 0
            val size = stack.size
            for (i in 0 until size) {
                val node = stack.get(0)
                stack.removeAt(0)
                oneLevelSum += node.`val`
                if (node.left != null) {
                    stack.add(node.left)
                }
                if (node.right != null) {
                    stack.add(node.right)
                }
            }
            map.put(oneLevelSum, level)
            max = Math.max(max, oneLevelSum)
            
        }
       for (key in map.keys) {
            if (key == max) {
                level = map.get(key)!!
                break
            }
        }
        return level
    }
}                        

 

1161. Maximum Level Sum of a Binary Tree

原文:https://www.cnblogs.com/johnnyzhao/p/11595459.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!