题目来源
/**
* 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)
{
if(root == NULL)
{
return true;
}
return Sequencetraversal(root);
}
private:
bool Sequencetraversal(TreeNode* root)
{
queue<TreeNode*> dataqueue;
TreeNode* l = NULL;
TreeNode* r = NULL;
bool leaf = false;
dataqueue.push(root);
while(!dataqueue.empty())
{
root = dataqueue.front();
dataqueue.pop();
l = root->left;
r = root->right;
/*一个节点有右孩子没有左孩子,则必不是完全二叉树*/
if(root->right != NULL && root->left == NULL)
{
return false;
}
// leaf = true 则表示开启了叶节点的判断
//
if(leaf && (r != NULL || l != NULL) )
{
return false;
}
if(l != NULL)
{
dataqueue.push(root->left);
}
if(r != NULL)
{
dataqueue.push(root->right);
}
else
{
leaf = true; //有右孩子没有左孩子 开启叶节点的判断
}
}
return true;
}
};