层序遍历的进阶版本,要考虑好各种情况,尤其在判断该层不是完全占满的各种条件。

import queue
class Solution:
    def isCompleteTree(self , root: TreeNode) -> bool:
        # write code here
        # 层序遍历,先找到该二叉树的层次,不同层次有不同层次的解法
        if not root:
            return True

        # 层序遍历
        q = queue.Queue()
        q.put(root)
        is_full_flag = True
        node = 1 
        while not q.empty():
            node_num = q.qsize()
            if is_full_flag and node_num < node:
                return False
            for i in range(node_num):
                temp =q.get()
                if is_full_flag:
                    if temp.left and temp.right:
                        q.put(temp.left)
                        q.put(temp.right)
                    elif not temp.left and temp.right:
                        return False
                    elif temp.left:
                        q.put(temp.left)
                        is_full_flag = False
                    else:
                        is_full_flag = False
                else:
                    if temp.left or temp.right:
                        return False
            node *= 2
        return True