662. Maximum Width of Binary Tree

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.

image.png

image.png

None的位置还是要占着,用[]会TLE,用deque

class Solution:
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0
        from collections import deque
        q,qq=deque([root]),deque()
        res = 0
        while q:
            res = max(res, len(q))
            while q:
                t=q.popleft()
                qq.append(t.left if t else None)
                qq.append(t.right if t else None)
            q,qq = qq, q
            while q and not q[0]: q.popleft()
            while q and not q[-1]: q.pop()
        return res

你可能感兴趣的:(662. Maximum Width of Binary Tree)