Skip to main content

662 Maximum Width of Binary Tree

LeetCode

Given the root of a binary tree, return 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 rightmost non-null nodes), 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: root = [1,3,2,5,3,null,9]
Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).

Example 2:

Input: root = [1,3,null,5,3]
Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).

Example 3:

Input: root = [1,3,2,5]
Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).


定义一个 id 来表示一行中的坐标,如果填满为完全二叉树,最左边 id 是 0 ,当前节点的左子树 id 为当前节点的 id 乘以 2 ,右子树为 id 乘以 2 加 1 。

使用两个 List 记录每一行的最小 id 和最大宽度。使用前序遍历,带着层数和 id 遍历,每一行的第一个遍历到的节点是最左的节点,更新当前行的最小 id ,其余节点不是最左节点,计算宽度并更新最大宽度。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {

ArrayList<Integer> levelMin;
ArrayList<Integer> levelMax;
public int widthOfBinaryTree(TreeNode root) {
if(root==null) return 0;

levelMin = new ArrayList<>();
levelMax = new ArrayList<>();
preOrder(root,0,0);
int max=0;
for(int i:levelMax){
if(i>max) max=i;
}
return max+1;
}

private void preOrder(TreeNode root, int depth, int id){

if(levelMin.size()==depth) {
levelMin.add(id);
levelMax.add(0);
} else {
int cur = id-levelMin.get(depth);
if(cur > levelMax.get(depth)) levelMax.set(depth,cur);
}


if(root.left!=null){
preOrder(root.left, depth+1, id*2);
}
if(root.right!=null){
preOrder(root.right, depth+1, id*2+1);
}

}
}