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:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
Example 2:
Input:
1
/
3
/ \
5 3
Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).
Example 3:
Input:
1
/ \
3 2
/
5
Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).
Example 4:
Input:
1
/ \
3 2
/ \
5 9
/ \
6 7
Output: 8
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.
题目链接:https://leetcode.com/problems/maximum-width-of-binary-tree/
题目分析:容易想到用BFS来做,对于每层,只要知道最左和最右的位置即可,对于一棵满二叉树按照层次遍历的顺序,若结点x的编号为k,则其左孩子编号为k*2,右孩子编号为k*2+1,据此性质可算出每层的最左和最右位置的编号
1ms,时间击败100%
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
class NodeInfo {
int label;
TreeNode node;
public NodeInfo(int label, TreeNode node) {
this.label = label;
this.node = node;
}
}
public int widthOfBinaryTree(TreeNode root) {
Queue<NodeInfo> q = new LinkedList<>();
q.offer(new NodeInfo(1, root));
int ans = 1;
while (!q.isEmpty()) {
int sz = q.size(), mi = Integer.MAX_VALUE, ma = 0;
for (int i = 0; i < sz; i++) {
NodeInfo cur = q.poll();
if (cur.node.left != null) {
int leftLabel = cur.label << 1;
ma = Math.max(ma, leftLabel);
mi = Math.min(mi, leftLabel);
q.offer(new NodeInfo(leftLabel, cur.node.left));
}
if (cur.node.right != null) {
int rightLabel = cur.label << 1 | 1;
ma = Math.max(ma, rightLabel);
mi = Math.min(mi, rightLabel);
q.offer(new NodeInfo(rightLabel, cur.node.right));
}
}
if (mi != Integer.MAX_VALUE && ma != 0) {
ans = Math.max(ans, ma - mi + 1);
}
}
return ans;
}
}