# 958. Check Completeness of a Binary Tree

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/check-completeness-of-a-binary-tree/

> 内容描述

```
Given a binary tree, determine if it is a complete binary tree.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

 

Example 1:



Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:



Input: [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

就是level order之后检查一下即可

```python
class Solution:
    def isCompleteTree(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def dfs(node, level, res):
            if len(res) < level:
                res.append([])
            if not node:
                res[level-1].append(None)
                return
            else:
                res[level-1].append(node.val)
            dfs(node.left, level+1, res)
            dfs(node.right, level+1, res)  
        
        def checkLeafLevel(lst):
            for i in range(len(lst)-1):
                if not lst[i] and lst[i+1]:
                    return False
            return True

        res = []
        dfs(root, 1, res)
        if not res or len(res) == 0:
            return True
        for i, lst in enumerate(res):
            if i < len(res) - 2:
                if len(lst) != 2 ** (i) or not all(j for j in lst):
                    return False
            if i == len(res) - 2:
                if not checkLeafLevel(lst):
                    return False
        return True
```
