题目描述
给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。
每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。
解题思路
1、错误示例:没有认真审题,忽略了两端点间的null节点也计入长度这个条件,结果是错的,错误示例是采用非递归的层序遍历,取层数最大值,忽略有空节点这个条件。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int widthOfBinaryTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
int width = 0;
if(root == null) return width;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
width = Math.max(width, size);
while(size-- > 0){
TreeNode node = queue.poll();
if(node.left != null)
queue.offer(node.left);
if(node.right != null){
queue.offer(node.right);
}
}
}
return width;
}
}
2、更改:考虑到在这道题的结点值没有什么用,我们这里把变量val用来记录结点的索引值。
用到的知识点:
(1)对于任意结点的索引值为i, 其结点的左孩子的索引是2i,右孩子的索引是2i + 1
(2) peekFirst()表示列表的第一个元素(检索但不删除此列表的第一个元素,如果此列表为空,则返回null)
(3)peekLast() 表示列表的最后一个元素
注意:
root.val = 0;
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int widthOfBinaryTree(TreeNode root) {
if(root == null) return 0;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
root.val = 0;
int max = 1;
while(!queue.isEmpty()){
int size = queue.size();
max = Math.max(max, queue.peekLast().val - queue.peekFirst().val + 1);
for(int i = 0; i < size; i++){
root = queue.poll();
if(root.left != null){
root.left.val = root.val * 2;
queue.offer(root.left);
}
if(root.right != null){
root.right.val = root.val * 2 + 1;
queue.offer(root.right);
}
}
}
return max;
}
}
参考:https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/106663/Java-O(n)-BFS-one-queue-clean-solution