关于二叉树建立的几种方法

来源:互联网 发布:网络谣传实例 编辑:程序博客网 时间:2024/05/17 20:33

1.先根序递归法建立二叉树(针对不需要总是问询的情况,本人认为是最简单的一种方法)

CreateTree(node *T){   char a;   cin>>a;  if(a=='#'){     T=NULL;}  else{    T=new node;//T=(node *)malloc(sizeof(node));    T->data=a;    CreateTree(T->left);    CreateTree(T->right);}}
或者

Node* Create(){  node *t=NULL;   char a;   cin>>a;    if(a!='#')   {       t=new node;       t->data=a;       bt->left=Create();       bt->right=Create();       }   return t;}


example:             a

                        b       c                   输入为ab##c##

2.与用户交互的方式,根据用户输入根节点,data,parent,l/r;

node *find;CreateTree(node *p){  char sign;  p=new node();  cout<<"Input root:";  cin>>p->data;  do{       cout<<"Input data ,parent, L/R:"       char c;       int t,par;       cin>>t>>par>>c;            node *temp=new node;      temp->data=t;      if(c=='L')        {             find->left=temp;         }      else       {              find->right=temp;        }         cout<<"Any else?------y/n";          cin>>sign;      }while(sign=='y');} void Find(node *p,int par){     if(p1!=NULL)      {       if(p->data==par)       {         find=p;            return;        }       else       {           Find(p->left);           Find(p->right);        }       }}
原创粉丝点击