1161. Maximum Level Sum of a Binary Tree

短命女 2023-06-01 12:55 22阅读 0赞
  1. import java.util.*
  2. import kotlin.collections.HashMap
  3. /**
  4. * 1161. Maximum Level Sum of a Binary Tree
  5. * https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/
  6. * */
  7. class TreeNode(var `val`: Int) {
  8. var left: TreeNode? = null
  9. var right: TreeNode? = null
  10. }
  11. class Solution {
  12. fun maxLevelSum(root: TreeNode?): Int {
  13. var level = 0
  14. var max = 0
  15. val map = HashMap<Int, Int>()
  16. val stack = Stack<TreeNode>()
  17. stack.add(root)
  18. while (!stack.isEmpty()) {
  19. level++
  20. var oneLevelSum = 0
  21. val size = stack.size
  22. for (i in 0 until size) {
  23. val node = stack.get(0)
  24. stack.removeAt(0)
  25. oneLevelSum += node.`val`
  26. if (node.left != null) {
  27. stack.add(node.left)
  28. }
  29. if (node.right != null) {
  30. stack.add(node.right)
  31. }
  32. }
  33. map.put(oneLevelSum, level)
  34. max = Math.max(max, oneLevelSum)
  35. }
  36. for (key in map.keys) {
  37. if (key == max) {
  38. level = map.get(key)!!
  39. break
  40. }
  41. }
  42. return level
  43. }
  44. }

转载于:https://www.cnblogs.com/johnnyzhao/p/11595459.html

发表评论

表情:
评论列表 (有 0 条评论,22人围观)

还没有评论,来说两句吧...

相关阅读