题目

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

Example 1:

  1. Input:
  2. 1
  3. / \
  4. 3 2
  5. / \ \
  6. 5 3 9
  7. Output: 4
  8. Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).

Example 2:

  1. Input:
  2. 1
  3. /
  4. 3
  5. / \
  6. 5 3
  7. Output: 2
  8. Explanation: The maximum width existing in the third level with the length 2 (5,3).

Example 3:

  1. Input:
  2. 1
  3. / \
  4. 3 2
  5. /
  6. 5
  7. Output: 2
  8. Explanation: The maximum width existing in the second level with the length 2 (3,2).

Example 4:

  1. Input:
  2. 1
  3. / \
  4. 3 2
  5. / \
  6. 5 9
  7. / \
  8. 6 7
  9. Output: 8
  10. Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).

Note: Answer will in the range of 32-bit signed integer.


题意

找到给定二叉树的最大宽度,每层的宽度定义为每层第一个非空结点到最后一个非空结点的距离。

思路

层序遍历。建两个队列,一个记录结点,一个记录对应结点在当前层的序号。


代码实现

Java

  1. class Solution {
  2. public int widthOfBinaryTree(TreeNode root) {
  3. Queue<TreeNode> nodes = new LinkedList<>();
  4. Queue<Integer> order = new LinkedList<>();
  5. int max = 0;
  6. if (root != null) {
  7. nodes.offer(root);
  8. order.offer(0);
  9. }
  10. while (!nodes.isEmpty()) {
  11. int size = nodes.size();
  12. int start = 0, end = 0;
  13. for (int i = 0; i < size; i++) {
  14. TreeNode cur = nodes.poll();
  15. int num = order.poll();
  16. start = i == 0 ? num : start;
  17. end = i == size - 1 ? num : end;
  18. if (cur.left != null) {
  19. nodes.offer(cur.left);
  20. order.offer(num * 2);
  21. }
  22. if (cur.right != null) {
  23. nodes.offer(cur.right);
  24. order.offer(num * 2 + 1);
  25. }
  26. }
  27. max = Math.max(max, end - start + 1);
  28. }
  29. return max;
  30. }
  31. }