原题
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:
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).
解法1
我们假设树是完全二叉树, 这样可以对每个节点计数, 我们设根节点的序号为1, 在第n个节点时, 它的左子树是第2n个节点, 它的右子树是2n+1个节点, 然后使用BFS, 如果子树存在的话, 将序号放入列表中, 宽度是 = 最右边的序号 - 最左边的序号 + 1, 每次循环时更新res. 我们使用deque存放每层节点.
Time: O(n)
Space: O(n)
代码
class Solution:
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# base case
if not root: return 0
q = collections.deque()
q.append((root, 1))
res = 0
while q:
width = q[-1][1] - q[0][1] + 1
res = max(res, width)
for i in range(len(q)):
node, count = q.popleft()
if node.left:
q.append((node.left, 2*count))
if node.right:
q.append((node.right, 2*count + 1))
return res
解法2
同解法1, 使用列表存放每层的节点
代码
class Solution:
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# base case
if not root: return 0
q = [(root, 1)]
res = 0
while q:
width = q[-1][1] - q[0][1] + 1
res = max(res, width)
new_q = []
for tup in q:
node, count = tup[0], tup[1]
if node.left:
new_q.append((node.left, 2*count))
if node.right:
new_q.append((node.right, 2*count + 1))
q = new_q
return res