题目描述
给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。
每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。
示例 1:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: 4
解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。
示例 2:
输入:
1
/
3
/ \
5 3
输出: 2
解释: 最大值出现在树的第 3 层,宽度为 2 (5,3)。
示例 3:
输入:
1
/ \
3 2
/
5
输出: 2
解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)。
示例 4:
输入:
1
/ \
3 2
/ \
5 9
/ \
6 7
输出: 8
解释: 最大值出现在树的第 4 层,宽度为 8 (6,null,null,null,null,null,null,7)。
题解
层序遍历代码
/**
* 层序遍历,记录每个节点的索引,
* 当每层遍历完成后计算下一层的最大宽度(链表最后一个元素索引-链表的最前面元素索引+1)
*/
public int widthOfBinaryTree(TreeNode root) {
int maxW=1;
if (root == null)
return 0;
/*层序遍历存储节点*/
Queue<TreeNode> queue = new LinkedList<>();
LinkedList<Integer> indexList = new LinkedList<>();
queue.add(root);
/*存储索引*/
indexList.add(1);
int size = 1;
/*如果队列不为空*/
while (!queue.isEmpty()) {
/*队首元素出队*/
TreeNode node = queue.poll();
size--;
int index = indexList.removeFirst();
/*左节点不为空则入队列*/
if (node.left != null) {
queue.add(node.left);
indexList.add(2 * index);
}
/*右节点不为空则入队列,而且对应的节点树相当于加2*/
if (node.right != null) {
queue.add(node.right);
indexList.add(2 * index + 1);
}
/*size为该层的全部节点数,如果size==0说
明当前的节点都已经循环完毕*/
if (size == 0) {
if (indexList.size() >= 2) {
/*判断·*/
maxW = Math.max(maxW, indexList.getLast() - indexList.getFirst() + 1);
}
size = queue.size();
}
}
return maxW;
}
代码理解
indexList就是存储每个节点的索引
LinkedList<Integer> indexList = new LinkedList<>();