题解 | #二叉树的最大宽度#

二叉树的最大宽度

https://www.nowcoder.com/practice/0975d62a307549cea32f353f354a7377

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 widthOfBinaryTree (TreeNode root) {
        // write code here
        if(root == null) return 0;
        int maxWidth = 0;
        Queue<Pair> q = new LinkedList<>();
        q.offer(new Pair(root, 1));
        while(!q.isEmpty()) {
            int sz = q.size();
            int start = 0, end = 0;
            for(int i = 0; i < sz; i++) {
                Pair curPair = q.poll();
                TreeNode curNode = curPair.node;
                int curId = curPair.id;
                if(i == 0) {
                    start = curId;
                }
                if(i == sz-1) {
                    end = curId;
                }
                if(curNode.left != null) {
                    q.offer(new Pair(curNode.left, curId * 2));
                }
                if(curNode.right != null) {
                    q.offer(new Pair(curNode.right, curId * 2 + 1));
                }
            }
            maxWidth = Math.max(maxWidth, end - start + 1);
        }
        return maxWidth;
    }
}

class Pair {
    TreeNode node;
    int id;

    public Pair(TreeNode node, int id) {
        this.node = node;
        this.id = id;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
02-26 16:57
明天不下雨了:把第二个项目放第一个去,其他没什么问题,多投,这世道就这样
点赞 评论 收藏
分享
用户64975461947315:这不很正常吗,2个月开实习证明,这个薪资也还算合理,深圳Java好多150不包吃不包住呢,而且也提前和你说了没有转正机会,现在贼多牛马公司骗你说毕业转正,你辛辛苦苦干了半年拿到毕业证,后面和你说没hc了😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务