Maximum Width if Binary Tree

public 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;
		}
}

最后更新于

这有帮助吗?