662. 二叉树最大宽度

195 阅读1分钟

注意: 取的是非空端点间的长度

思路:

  • 不能简单层序遍历,算每层上的节点个数(queue.size()),因为取的是非空端点间的长度并且中间的null也算。
  • 给每个非空节点标号,空节点算数。
  • 然后每层的宽度 = 首尾非空节点标号之差+1
  • 搞一个队列记录编号,与记录节点的队列同步。

class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();//记录node的队列
        LinkedList<Integer> indexQ = new LinkedList<>();//记录index的队列,这俩同步进出
        queue.add(root);
        indexQ.add(0);
        int max = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            int start = indexQ.getFirst();
            int end = indexQ.getLast();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.removeFirst();//同步出列
                int index = indexQ.removeFirst();//同步出列
                if (node.left != null) {
                    queue.add(node.left);//同步入列
                    indexQ.add(index * 2 + 1);//同步入列
                }
                if (node.right != null) {
                    queue.add(node.right);//同步入列
                    indexQ.add(index * 2 + 2);//同步入列
                }
            }
            int idxSize = end - start + 1;//不能在这里getLastFirst,这里get的话是下一行的。如果是最后一行的话到这里idxQ已经空了
            max = Math.max(idxSize, max);

        }
        return max;
    }
}