二叉樹的建立

來源:互聯網
上載者:User

一:根據擴充二叉樹的前序走訪序列建立該二叉樹

Binode* Creat(Binode* bt){char ch;cin>>ch;if(ch=='#')bt=NULL;else{bt=new Binode;bt->data=ch;bt->lchild=Creat(bt->lchild);bt->rchild=Creat(bt->rchild);}return bt;}

二:根據二叉樹的前序走訪和中序遍曆序列建立該二叉樹

這是一個遞迴的過程,其基本思想是:先根據前序序列的第一個元素建立根節點,然後在中序序列中找到該元素,確定了根節點的左右子樹的中序序列,再在前序序列中確定左右子樹的前序序列,最後由左子樹的前序和中序建立左子樹,由右子樹的前序和中序建立右子樹

int pos(char ch,char *pin,int i2)//尋找根節點在中序序列中的位置{for(int i=i2;i<k;i++)if(*(pin+i)==ch)return i;}

 

BiNode* Creat(BiNode *root,int i1,int i2,int k){//i1為前序的起始下標,i2為中序的起始下標,k為序列的長度,pre[]為前序序列,pin為中序序列if(k<=0)root=NULL;else{root=new BiNode;root->data=pre[i1];int m=Search(pre[i1],pin,i2);//尋找根節點在中序序列中的位置int leftlen=m-i2;int rightlen=k-(leftlen+1);root->lchild=Creat(root->lchild,i1+1,i2,leftlen);root->rchild=Creat(root->rchild,i1+leftlen+1,m+1,rightlen);}return root;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.