二叉树的宽度

二叉树的宽度即为二叉树每层的节点数最多的那一层的宽度,由此我们得出思路,可以通过层次遍历,记录每层的节点个数,最后得出二叉树的宽度,代码如下:

def get_width(self,root):
    if not root:
        return 0
    max_width=0
    q=[root]
    while q:
        max_width=max(max_width,len(q))
        q1=[]
        while q:
            node=q.pop()
            if node.left:
                q1.append(node.left)
            if node.right:
                q1.append(node.right)
        q=q1[:]
    return max_width