完全二叉树的定义是,前n-1层都是满的,第n层如有空缺,则是缺在右边,即第n层的最右边的节点,它的左边是满的,右边是空的
根据层序遍历遍历二叉树,直到发现一个空节点,若树种还有未被访问的非空节点,则该二叉树不是完全二叉树
template<class T>
struct BinaryTreeNode
{
BinaryTreeNode(T& data)
:_data(data)
, _pLeftChild(NULL)
, _pRighChild(NULL)
{}
T _data;
BinaryTreeNode<T>* _pLeftChild;
BinaryTreeNode<T>* _pRighChild;
};
template<class T>
bool IsComBianaryTree(BinaryTreeNode<T>*pRoot)
{
//空树也属于完全二叉树
if (pRoot == NULL)
return true;
//层序遍历找到一个空节点
queue<BinaryTreeNode<T>*> q;
q.push(pRoot);
while (q.front() != NULL)
{
BinaryTreeNode<T>* Node = q.front();
q.pop();
q.push(Node->_pLeftChild);
q.push(Node->_pRighChild);
}
q.pop();//空节点出队列
//当前节点为空,若是完全二叉树则之后未被访问到的节点必须为空,若不为空,则不是完全二叉树
while (!q.empty())
{
if (q.front() != NULL)
return false;
else
return true;
}
return true;
}