[LeetCode]662. Maximum Width of Binary Tree判断树的宽度

public int widthOfBinaryTree(TreeNode root) {
        /*
        层序遍历+记录完全二叉树的坐标,左孩子2*i,右孩子2*i+1
        而且要有两个变量,一个记录本层节点数,一个记录下层节点数
        层序遍历用队列实现
        还要有一个队列记录本层的下标
         */
        //层序遍历记录节点
        Queue<TreeNode> tree = new LinkedList<>();
        //记录每个节点的位置,用来判断此节点的孩子的坐标
        Queue<Integer> index = new LinkedList<>();
        //当前层数量和下一层数量
        int cur = 1;
        int next = 0;
        //本层开始坐标和结束坐标
        int sta = 1;
        int end = 1;
        //记录结果
        int res = 0;
        tree.offer(root);
        index.offer(1);
        while (!tree.isEmpty())
        {
            //当前节点和坐标
            TreeNode curTree = tree.poll();
            end = index.poll();
            //添加左子树和坐标
            if (curTree.left!=null)
            {
                tree.offer(curTree.left);
                next++;
                index.offer(end*2);
            }
            //添加右子树和坐标
            if (curTree.right!=null)
            {
                tree.offer(curTree.right);
                next++;
                index.offer(end*2+1);
            }
            //本层待遍历节点数-1
            cur--;
            //本层遍历完毕,更新结果和下一层数据
            if (cur==0)
            {
                res = Math.max(res,end-sta+1);
                cur = next;
                next = 0;
                sta = index.isEmpty()?1:index.peek();
            }
        }
        return res;
    }
原文地址:https://www.cnblogs.com/stAr-1/p/8413799.html