给你一棵二叉树的根节点 root ,返回树的 最大宽度 。
树的 最大宽度 是所有层中最大的 宽度 。
每一层的 宽度 被定义为该层最左和最右的非空节点(即,两个端点)之间的长度。将这个二叉树视作与满二叉树结构相同,两端点间会出现一些延伸到这一层的 null 节点,这些 null 节点也计入长度。
示例1:
输入:root = [11,12,13,null,14] 输出:2 解释:最大宽度出现在树的第 2 层,宽度为 2 (12,13) 。
这道题其实是利用二叉树的性质,每一层的下标规则:左子树下标=父节点下标*2;右子树下标=父节点下标*2+1;如下图所示:

这里在原来树结构的基础上,增进position,用于记录每个节点的下标,整个类如下:
TreeNode
package org.example;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode() {
}
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
TreeNodeExtend
class TreeNodeExtend { TreeNode node; int position; public TreeNodeExtend(TreeNode node, int position) { this.node = node; this.position = position; } }
接着使用BFS进行遍历,这里我使用LinkedList模拟队列操作,具体代码实现如下:
-
- import org.example.TreeNode;
-
- import java.util.LinkedList;
-
- class Solution {
-
-
- public int widthOfBinaryTree(TreeNode root) {
-
- if (root == null) {
- return 0;
- }
-
- LinkedList
deque = new LinkedList<>(); - deque.offer(new TreeNodeExtend(root, 0));
-
- int max = 1;
-
- while (!deque.isEmpty()) {
-
- max = Math.max(max, deque.get(deque.size() - 1).position - deque.get(0).position + 1);
- int sz = deque.size();
- for (int i = 0; i < sz; i++) {
- TreeNodeExtend node = deque.poll();
-
- if (node.node.left != null) {
- deque.offer(new TreeNodeExtend(node.node.left, node.position * 2));
- }
-
- if (node.node.right != null) {
- deque.offer(new TreeNodeExtend(node.node.right, node.position * 2 + 1));
- }
- }
- }
- return max;
- }
-
- class TreeNodeExtend {
-
- TreeNode node;
- int position;
-
- public TreeNodeExtend(TreeNode node, int position) {
- this.node = node;
- this.position = position;
- }
- }
-
-
- }

这道题就是2-3个简单问题组合到一起的中等难度问题;核心问题有:
- 二叉树的层序遍历,BFS;
- 二叉树的性质-下标生成的规则,并且构造有下标的二叉树;
- 最大值的获取。
这道题按照上述解法,耗时1ms左右。如果有更高效、更简洁的思路欢迎回复。