L3-010. 是否完全二叉搜索树

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

输入格式:

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

输出格式:

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

输入样例1:

9
38 45 42 24 58 30 67 12 51

输出样例1:

38 45 24 58 42 30 12 67 51
YES

输入样例2:

8
38 24 12 45 58 67 42 51

输出样例2:

38 45 24 58 42 12 67 51
NO

对节点标号,相邻标号只有一个孩子的节点或叶子节点和叶子节点至多相差一,但要注意左单枝的情况,最后一个测试点就是左单枝的情况,判断一下是不是有右孩子但是没有左孩子即可。

#include<bits/stdc++.h>

using namespace std;

const int N = 100 + 5;

struct node{
    int key, floor, lchild, rchild;
    node(){
        floor = lchild = rchild = 0;
    }
} Node[N];

int n, st = 0, root = 0;

vector<int> v;
void BFS(){
    queue<int> Q;

    Q.push(root);
    Node[root].floor = 1;
    int cnt = 0;
    while(!Q.empty()){
        int tmp = Q.front(); Q.pop();
        printf("%d%c", Node[tmp].key, (--n ?' ':'
'));
        if(Node[tmp].lchild != 0){
            int x = Node[tmp].lchild;
            Node[x].floor = Node[tmp].floor + 1;
            Q.push(x);
        }

        if(Node[tmp].rchild != 0){
            int x = Node[tmp].rchild;
            Node[x].floor = Node[tmp].floor + 1;
            Q.push(x);
        }
        if(!Node[tmp].lchild || !Node[tmp].rchild)
            v.push_back(cnt);
        if(!Node[tmp].lchild && Node[tmp].rchild)    //避免左单枝
            v.push_back(100);
        cnt++;
    }
}

void Create(int & root, int key){
    if(root == 0) {
        root = ++st;
        Node[root].key = key;
        return;
    }else if(key > Node[root].key){
        Create(Node[root].lchild, key);
    }else {
        Create(Node[root].rchild, key);
    }
}
int main(){

    cin >> n;
    int key;
    for(int i = 0; i < n; i++){
        cin >> key;
        Create(root, key);
    }
    BFS();
    for(int i = v.size() - 1; i > 0; i --){
        if(v[i] != v[i-1]  + 1){
            printf("NO
");
            return 0;
        }
    }
    printf("YES");
}
原文地址:https://www.cnblogs.com/Pretty9/p/8669893.html