7-2 是否完全二叉搜索树 (30 分)

题目:

将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。

输入格式:

输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。

输出格式:

将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES,如果该树是完全二叉树;否则输出NO

思路:

1、按照题目要求进行建树。

2、判断树是否为完全树的方法是对树进行BFS遍历,当遇到NULL的时候退出,记录遍历到的点的个数cnt。如果cnt==总的节点数则是完全树,否则不是。

3、利用队列进行树的层次遍历。

代码:

#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
#define MAX 1e9;
#define FRE() freopen("in.txt","r",stdin)
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int maxn = 200;
int N;
typedef struct BNode {
    int value;
    struct BNode *rt, *lt;
} BNode, *BTree;

struct BitTree {

    void initTree(BTree& tree) {
        tree = NULL;
    }

    void insertNode(int x, BTree& T) {
        if(!T) {
            T = (BTree)malloc(sizeof(BNode));
            T->value = x;
            T->lt = NULL;
            T->rt = NULL;
            //cout<<"LL"<<endl;
            return;
        }
        if(x >= T->value) {
            insertNode(x, T->lt);
        } else if(x < T->value) {
            insertNode(x, T->rt);
        }
    }

    bool judge(BTree& tree) {
        if(!tree)
        { return true; }

        queue<BTree> que;
        int cnt = 0;
        que.push(tree);
        BTree temp;
        while((temp = que.front()) != NULL){
            que.pop();
            cnt++;
            que.push(temp->lt);
            que.push(temp->rt);
            //cout<<temp->value<<"GG"<<endl;
        }
        //cout<<cnt<<"KK"<<endl;
        if(cnt == N){
            return true;
        }else{
            return false;
        }
    }

    void print(BTree& tree){
        //cout<<tree->lt->value<<" GG"<<endl;
        int path[maxn];
        int idx = 0;
        queue<BTree> que;
        que.push(tree);

        while(!que.empty()){
            BTree temp = que.front();
            path[idx++] = temp->value;
            if(temp->lt){
                que.push(temp->lt);
            }
            if(temp->rt){
                que.push(temp->rt);
            }
            que.pop();
        }
        for(int i = 0; i<idx; i++){
            if(i!=0)
                printf(" ");
            printf("%d",path[i]);
        }
        printf("\n");
    }

};


int main() {
    //FRE();
    BTree tree;
    BitTree Tree;
    Tree.initTree(tree);

    scanf("%d", &N);
    for(int i = 0; i<N; i++) {
        int t;
        scanf("%d", &t);
        Tree.insertNode(t,tree);
    }

    Tree.print(tree);
    if(Tree.judge(tree)){
        printf("YES\n");
    }else{
        printf("NO\n");
    }

    return 0;
}
/*
PutIn:
9
38 45 42 24 58 30 67 12 51
PutOut:
38 45 24 58 42 30 12 67 51
YES
PutInt:
8
38 24 12 45 58 67 42 51
PutOut:
38 45 24 58 42 12 67 51
NO
*/
View Code

 

posted @ 2018-12-05 12:43  sykline  阅读(740)  评论(0编辑  收藏  举报