题目
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.
答案
public int widthOfBinaryTree(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
Map<TreeNode, Integer> map = new HashMap<>();
int max = 1;
q.offer(root);
map.put(root, 0);
while(q.size() != 0) {
int curr_size = q.size();
int leftmost = Integer.MAX_VALUE, rightmost = Integer.MIN_VALUE, idx;
for(int i = 0; i < curr_size; i++) {
TreeNode t = q.poll();
if(t.left != null) {
q.offer(t.left);
idx = map.get(t) * 2 + 1;
map.put(t.left, idx);
leftmost = Math.min(leftmost, idx);
rightmost = Math.max(rightmost, idx);
max = Math.max(max, rightmost - leftmost + 1);
}
if(t.right != null) {
q.offer(t.right);
idx = map.get(t) * 2 + 2;
map.put(t.right, idx);
leftmost = Math.min(leftmost, idx);
rightmost = Math.max(rightmost, idx);
max = Math.max(max, rightmost - leftmost + 1);
}
}
}
return max;
}