题解 | #重量级的一层#

重量级的一层

https://www.nowcoder.com/practice/193372871b09426ab9ea805f0fd44d5c

还是对于二叉树层序遍历的考察。层序遍历的过程中就记录并更新最大的层间重量,将结果返回就可以了。

完整Java代码如下所示

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxLevelSum (TreeNode root) {
        int maxheight = -1;
        int ans = -1;
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int ceng = 0;
        while(!queue.isEmpty()){
            int sum = 0;
            int count = queue.size();
            ceng++;
            while(count-- >0){
                TreeNode node = queue.poll();
                sum+=node.val;
                if (node.left != null) {
					queue.add(node.left);
				}
				if (node.right != null) {
					queue.add(node.right);
				}
            }
            if(maxheight<=sum){
              ans=ceng;
              maxheight = sum;
            }
        }
        return ans;
    }
}

全部评论

相关推荐

10-21 00:37
已编辑
山东大学 C++
小浪_Coding:你问别人,本来就是有求于人,别人肯定没有义务免费回答你丫, 有点流量每天私信可能都十几,几十条的,大家都有工作和自己的事情, 付费也是正常的, 就像你请别人搭把手, 总得给人家买瓶水喝吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务