给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。
请你找出层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个。
示例 1:
输入:root = [1,7,0,7,-8,null,null]
输出:2
解释:
第 1 层各元素之和为 1,
第 2 层各元素之和为 7 + 0 = 7,
第 3 层各元素之和为 7 + -8 = -1,
所以我们返回第 2 层的层号,它的层内元素之和最大。
示例 2:
输入:root = [989,null,10250,98693,-89388,null,null,null,-32127]
输出:2
提示:
树中的节点数介于 1 和 10^4 之间
-10^5 <= node.val <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-level-sum-of-a-binary-tree
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { static int getHeight(TreeNode root) { if (root.left == null && root.right == null) return 0; int left = 0; if (root.left != null) left = getHeight(root.left); int right = 0; if (root.right != null) right = getHeight(root.right); return (Math.max(left, right) + 1); } // Recursive static void calculateLevelSum(TreeNode node, int level, int sum[]) { if (node == null) return; sum[level] += node.val; calculateLevelSum(node.left, level + 1, sum); calculateLevelSum(node.right, level + 1, sum); } public int maxLevelSum(TreeNode root) { int levels = getHeight(root) + 1; int sum[]=new int[levels]; calculateLevelSum(root, 0, sum); int highest=Integer.MIN_VALUE;; for (int counter = 0; counter < levels; counter++) { if (sum[counter] > highest) { highest = sum[counter]; } } int res=0; for (int counter = 0; counter < levels; counter++) { if (sum[counter] == highest) { res=counter; break; } } return res+1; } }