判断是否为完全二叉树

算法思想:采用层次遍历算法,将所有结点加入队列(包括空结点)。遇到空结点时,检查看其后是否有非空结点。若有,则二叉树不是完全二叉树。

#include
using namespace std;
typedef struct BiNode {
    char data;
    struct BiNode* lchild, * rchild;
}BiNode, * BiTree;
typedef struct stack {
    BiTree data[1024];
    int top;
}stack;
typedef struct queue {
    BiTree data[1024];
    int front;
    int rear;
}queue;
void create(BiTree& t) {//二叉树先序
    char ch;
    cin >> ch;
    if (ch == '@')t = NULL;
    else {
        t = new BiNode;
        t->data = ch;
        create(t->lchild);
        create(t->rchild);
    }
}
void preorder(BiTree t) {
    BiTree s[1024];
    int top = 0;
    BiTree p = t;
   
    while (p || top != 0) {
        if (p) {
            s[top++] = p;
            cout << p->data;
            p = p->lchild;
        }
        else {
            p = s[--top];
            p = p->rchild;
        }
    }
}
void inorder(BiTree t) {
    BiTree s[1024];
    int top = 0;
    BiTree p = t;
    while (p || top != 0) {
        if (p) {
            s[top++] = p;
            p = p->lchild;
        }
        else {
            p = s[--top];
            cout << p->data;
            p = p->rchild;
        }
    }
}
int Btdepth(BiTree T) {
      BiTree q[1024];
    int front = 0, rear = 0;
    BiTree p = T;
    q[rear++] = p;
    int level = 0;
    int last = rear;
    while (front < rear) {
        p = q[front++];
        if (p->lchild)q[rear++] = p->lchild;
        if (p->rchild)q[rear++] = p->rchild;
        if (front == last) {
            level++;
            last = rear;
        }
    }
    return level;
}
bool IsComplete(BiTree t) {
    if (!t)return true;//空树为满二叉树
    BiTree q[1024];

    int front = 0, rear = 0;
    BiTree p = t;
    q[rear++] = p;
    while (front != rear) {
        p = q[front++];
        if (p) {    
            q[rear++] = p->lchild;    //相当于把所有结点入队(包括空结点);
            q[rear++] = p->rchild;
        }
        else {    //结点为空,检查其后是否有非空结点
            while (front != rear) {
                p = q[front++];
                if (p)return false;   //结点非空,二叉树为非完全二叉树
            }
        }
    }
    return true;
}
int main() {
    BiTree t;
     create(t);//测试数据:abd@@e@@c@@
    //abcde先序
    //edcba中序
  
   /* preorder(t);
    inorder(t);*/
    if (IsComplete(t)) {
        cout << "二叉树为完全二叉树";
    }
    else {
        cout << "二叉树为非完全二叉树";
    }

}

你可能感兴趣的:(数据结构(树),算法,数据结构,c语言,c++)