image.png

    思路: 看到题第一眼,二叉树遍历,获取每一行的个数,bfs 发现null也算在内,需要对bfs进行改进 利用二叉树的性质 去掉任意的结点,不影响其他结点的位置索引
    当前结点的位置索引假设为n,那左结点的位置索引为 2n,右结点为 2n+1

    image.png

    1. public int widthOfBinaryTree(TreeNode root) {
    2. // 如果结点为空,则宽度为0
    3. if(root == null) {
    4. return 0;
    5. }
    6. // 记录最大宽度
    7. int width = 0;
    8. // 队列1,放入TreeNode结点
    9. Deque<TreeNode> queue1 = new LinkedList<>();
    10. // 队列2,放入结点的位置索引
    11. Deque<Integer> queue2 = new LinkedList<>();
    12. // 放入root结点
    13. queue1.offerLast(root);
    14. // 放入root结点的位置索引
    15. queue2.offerLast(1);
    16. while(!queue1.isEmpty()) {
    17. // 当前层的结点数量
    18. int size = queue1.size();
    19. // 记录当前层的最大宽度
    20. int tmpWidth = 0;
    21. // 用于判断是否为当前层的第一个结点
    22. boolean flag = false;
    23. int left = -1, right = -1;
    24. // 遍历当前层的所有结点
    25. while(size-- > 0) {
    26. TreeNode node = queue1.pollFirst();
    27. int pos = queue2.pollFirst();
    28. // 遇到第一个结点
    29. if(!flag) {
    30. flag = true;
    31. left = pos;
    32. }
    33. right = pos;
    34. // 不停更新当前层的最大宽度
    35. tmpWidth = Math.max(tmpWidth, right-left+1);
    36. if(node.left != null) {
    37. queue1.offerLast(node.left);
    38. queue2.offerLast(pos*2);
    39. }
    40. if(node.right != null) {
    41. queue1.offerLast(node.right);
    42. queue2.offerLast(pos*2+1);
    43. }
    44. }
    45. width = Math.max(width, tmpWidth);
    46. }
    47. return width;
    48. }