Given a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels.
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.
It is guaranteed that the answer will in the range of 32-bit signed integer.
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).
Constraints:
The given binary tree will have between 1 and 3000 nodes.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-width-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
层次遍历,用一个map来储存当前节点,以及它在的位置。位置指按数组储存树的结构,所在的位置,即当前位置是i,那么它的左右子树,就是i * 2 与 i * 2 + 1。
class Solution {
public int widthOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
Queue<Pair<TreeNode, Integer>> queue = new ArrayDeque();
queue.add(new Pair<>(root , 1));
int result = 0;
while (!queue.isEmpty()) {
int levelNum = queue.size();
Pair<TreeNode, Integer> pair = queue.peek();
// start表示这一层的最左的节点的位置
int start = pair.getValue();
int end;
for (int i = 0; i < levelNum; i++) {
Pair<TreeNode, Integer> node = queue.remove();
TreeNode treeNode = node.getKey();
int position = node.getValue();
// end表示这一层的最右的节点的位置
end = position;
if (treeNode.left != null) {
queue.add(new Pair<>(treeNode.left, position * 2));
}
if (treeNode.right != null) {
queue.add(new Pair<>(treeNode.right, position * 2 + 1));
}
result = Math.max(result, end - start + 1);
}
}
return result;
}
}