One Leetcode per day-662. Maximum width of binary tree [level traversal]

Insert picture description here

/**
 * 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 {
    
    
    public int widthOfBinaryTree(TreeNode root) {
    
    
        if(root==null) return 0;
        // 层次遍历。定义一个队列
        Queue<TreeNode> q = new LinkedList<>();
        LinkedList<Integer> list = new LinkedList<>();
        // 根节点入队,根节点对应的下标为1,宽度为1
        q.offer(root);
        list.add(1);
        int res = 1;
        // 二叉树的下标:左子树节点 2*i, 右子树 2*i+1
        while(!q.isEmpty()){
    
    
            // 队列不为空
            int count = q.size();
            //遍历每层
            for(int i=count;i>0;i--){
    
    
                TreeNode cur = q.poll();
                Integer curIndex = list.removeFirst();
                if(cur.left!=null){
    
    
                    q.offer(cur.left);
                    list.add(curIndex*2);
                }
                if(cur.right!=null){
    
    
                    q.offer(cur.right);
                    list.add(curIndex*2+1);
                }
            }
            if(list.size()>=2){
    
    
                // list size为1,res也为1
                res = Math.max(res,list.getLast()-list.getFirst()+1);
            }
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/weixin_41041275/article/details/112600717