美文网首页
662. Maximum Width of Binary Tre

662. Maximum Width of Binary Tre

作者: GoDeep | 来源:发表于2018-05-05 16:00 被阅读0次

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 Tre

      本文链接:https://www.haomeiwen.com/subject/atcerftx.html