662. Maximum Width of Binary Tree

problem description

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.

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:

Example 4:

algorithm thought

这题是求每一层的宽度。如果要求宽度,关键是要得到最左和最右节点的位置,然后将两个位置相减就行。关键是如何安排每个节点的值。这里可以用类似heap的表示法。

如果first index base 1,它的子树就是 2index , 2index+1. 如果first index base 0,它的子树就是 2index+1 , 2index+2

然后用DFS或者是BFS遍历数,将最右的值减去最左的值即可。但是如果就这样,不加处理,会在最后两个case失败。因为我们用int类型表达index,这样树最多只能有32层。如果用long类型,树也只能有64层,这两种类型都不能通过测试。

于是我参考了下discuss,发现有人在进入下一层的时候,将index module INT_MAX。保证不溢出。修改代码之后发现能通过。

code

algorithm analysis

DFS遍历树,每次遍历中间时间复杂度为O(1),最后时间复杂度O(n)

Last updated