由初始序列构造二叉搜索树,输出层次遍历,并判断是否是完全二叉树

来源:互联网 发布:腾讯qq软件管理 编辑:程序博客网 时间:2024/05/18 02:37
 是否完全二叉搜索树 

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

输入格式:

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

输出格式:

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

输入样例1:

938 45 42 24 58 30 67 12 51

输出样例1:

38 45 24 58 42 30 12 67 51YES

输入样例2:

838 24 12 45 58 67 42 51

输出样例2:

38 45 24 58 42 12 67 51NO
题目地址:https://www.patest.cn/contests/gplt/L3-010
#include <iostream>#include <cstdio>#include <cmath>#include <queue>#include <stack>#include <map>#include <algorithm>#include <vector>#include <string>#include <cstring>#include <sstream>using namespace std;struct Btree{    int data;    Btree *left;    Btree *right;};typedef struct Btree Btree;int a[100];int n;Btree *root;void Insert(int x){    if(root==NULL)    {        root=new Btree;        root->data=x;        root->left=root->right=NULL;        return;    }    else    {        Btree *p=root,*q=NULL;        while(p)        {            q=p;            if(x>p->data)            {                p=p->left;            }            else            {                p=p->right;            }        }        p=new Btree;        p->data=x;        p->left=NULL;        p->right=NULL;        if(x>q->data) q->left=p;        else q->right=p;    }}int ans[100];queue<Btree*> Q;int cur;bool Cenorder(){    int flag=0;    int judge=0;    Q.push(root);    while(!Q.empty())    {        Btree *tmp=Q.front();        Q.pop();        ans[cur++]=tmp->data;        if(tmp->left)        {            Q.push(tmp->left);            if(flag==1)            {                judge=1;            }        }        else        {            flag=1;        }        if(tmp->right)        {            Q.push(tmp->right);            if(flag==1)            {                judge=1;            }        }        else        {            flag=1;        }    }    return judge==0;}int main(){    scanf("%d",&n);    for(int i=0;i<n;i++)    {        scanf("%d",&a[i]);    }    root=NULL;    for(int i=0;i<n;i++)    {        Insert(a[i]);    }    int judge=Cenorder();    for(int i=0;i<cur;i++)    {        if(i==0) printf("%d",ans[i]);        else printf(" %d",ans[i]);    }    printf("\n");    if(judge)    {        printf("YES\n");    }    else    {        printf("NO\n");    }    return 0;}


0 0
原创粉丝点击