题解 | #二叉树的最大宽度#
二叉树的最大宽度
http://www.nowcoder.com/practice/0975d62a307549cea32f353f354a7377
层序遍历改造
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public int widthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
LinkedList<Node> queue = new LinkedList<>();
queue.add(new Node(root, 0));
int maxWidth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
int firstIndex = queue.peekFirst().pos, lastIndex = queue.peekLast().pos;
maxWidth = Math.max(maxWidth, lastIndex - firstIndex + 1);
for (int i = 0; i < size; i++) {
Node node = queue.poll();
if (node.root.left != null) {
queue.add(new Node(node.root.left, node.pos << 1));
}
if (node.root.right != null) {
queue.add(new Node(node.root.right, (node.pos << 1) | 1));
}
}
}
return maxWidth;
}
class Node {
TreeNode root;
int pos;
public Node(TreeNode root, int pos) {
this.root = root;
this.pos = pos;
}
}
}