二叉樹——(先序序列+中序序列)=後序序列

來源:互聯網
上載者:User

已知二叉樹的先序遍曆序列和中序遍曆序列,求後序遍曆序列。

 

先遞迴構造二叉樹,然後遞迴得到後序序列。

 

思路:

 

先序序列的第一個結點為要構造二叉樹的根結點,在中序序列中尋找二叉樹的根結點,則中序列根結點左邊為根結點的左子樹的中序序列,右邊為根結點的右子樹的中序序列。而先序序列根結點後面分別為它的左子樹和右子樹的先序序列。有了根結點在中序序列的位置,就知道了左子樹和右子樹的先序序列各自的位置。這樣,就知道了根結點兩個子樹的序列。

然後在構造了根結點後,就可以遞迴調用函數來勾結根結點的左子樹和右子樹。

 

以上為二叉樹的恢複。

 

後序遍曆二叉樹也是用遞迴即可。

 

代碼如下:

 

string.find()   返回尋找元素的下標

string.substr(a, b)   從第a個下標的元素開始截取b個元素 

 代碼如下:

#include<iostream>#include<cstdio>#include<string>using namespace std;struct Node{char data;Node * lchild;Node * rchild;};Node* CreatTree(string pre, string in){Node * root = NULL;  //樹的初始化if(pre.length() > 0){root = new Node;  //為根結點申請結構體所需要的記憶體root->data = pre[0]; //先序序列的第一個元素為根結點int index = in.find(root->data);  //尋找中序序列中的根結點位置root->lchild = CreatTree(pre.substr(1, index), in.substr(0, index));  //遞迴建立左子樹root->rchild = CreatTree(pre.substr(index + 1), in.substr(index + 1)); //遞迴建立右子樹}return root;}void PostOrder(Node * root)  //遞迴後序遍曆{ if(root != NULL){PostOrder(root->lchild);PostOrder(root->rchild);cout<<root->data;}}int main(){string pre_str, in_str;Node *root;while(cin>>pre_str>>in_str){root = CreatTree(pre_str, in_str);PostOrder(root);cout<<endl;}return 0;}        

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.