958. 二叉树的完全性检验

给定一个二叉树,确定它是否是一个完全二叉树。

若设二叉树的深度为 h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。(注:第 h 层可能包含 1~ 2h 个节点。)

Solution1(迭代版):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
bool havenullnode = false;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* node = q.front();
q.pop();
if(!node){
havenullnode = true;
}else{
if(havenullnode) return false;
q.push(node->left);
q.push(node->right);
}
}
return true;
}
};

思路:

使用层序遍历,完全二叉树的遍历结果为只要遇到了null结点,之后的结点也都为null结点,否则就不是完全二叉树。

Solution2(递归版):