L2-004. 这是二叉搜索树吗?

来源:互联网 发布:果壳网和知乎 编辑:程序博客网 时间:2024/06/04 18:35

给一颗二叉搜索树的前序遍历,问你这是一颗二叉搜索树吗。

在创建的时候,一旦往树的右边创建,就不能往左边走了,否者就GG。


#include <iostream>#include <stdio.h>#include <string.h>#include <malloc.h>using namespace std;struct node{    int x;    bool l,r;    struct node *left;    struct node *right;};int p[1005];int l,r;int flag;struct node *newtree(struct node *t,int a){    struct node *p,*q;    p=t;    if(l==1){        while(p!=NULL){        if(a>=p->x){                p->l=0;                q=p;            p=p->right;        }        else{            if(p->l==1){                q=p;            p=p->left;            }            else{                flag=1;                break;            }        }    }}    else if(l==0)    while(p!=NULL){        if(a>=p->x){               // cout<<p->r<<" "<<p->x<<" "<<a<<endl;                if(p->r==1){                     q=p;            p=p->right;                }              else{                flag=1;                break;              }        }        else{            p->r=0;            q=p;            //cout<<p->x<<" "<<p->r<<endl;            p=p->left;        }    }    p=(struct node *)malloc(sizeof(struct node));        p->x=a;       // cout<<p->x<<endl;        if(a>=q->x){            q->right=p;        }        else q->left=p;        p->l=1;        p->r=1;        p->left=NULL;        p->right=NULL;    return t;}void houxu(node *t){    node *p;    p=t;    if(p==NULL) return ;    houxu(p->left);    houxu(p->right);    if(flag==0){       cout<<p->x;       flag=1;    }    else{        cout<<" "<<p->x;    }}void houxu1(node *t){    node *p;    p=t;    if(p==NULL) return ;    houxu1(p->right);    houxu1(p->left);    if(flag==0){       cout<<p->x;       flag=1;    }    else{        cout<<" "<<p->x;    }}int main(){    int n;    while(scanf("%d",&n)!=EOF){        node *tree;        flag=0;        for(int i=0;i<n;i++){            scanf("%d",&p[i]);        }        tree=(struct node *)malloc(sizeof(struct node));        tree->x=p[0];       // cout<<tree->x<<endl;        if(p[1]<p[0]){            l=1;            r=0;        }else{            l=0;            r=1;        }        //tree=NULL;        tree->left=NULL;        tree->right=NULL;        tree->l=1;        tree->r=1;        for(int i=1;i<n;i++){            tree=newtree(tree,p[i]);            //cout<<tree->x<<endl;        }        //cout<<tree->x<<endl;        if(flag==0)        {            printf("YES\n");            //printf("")            if(l==1)            houxu(tree);            else {                    houxu1(tree);            }        }        else{            printf("NO");        }        cout<<endl;    }    return 0;}


0 0
原创粉丝点击