已知二叉樹的先序遍曆序列和中序遍曆序列,求後序遍曆序列。
先遞迴構造二叉樹,然後遞迴得到後序序列。
思路:
先序序列的第一個結點為要構造二叉樹的根結點,在中序序列中尋找二叉樹的根結點,則中序列根結點左邊為根結點的左子樹的中序序列,右邊為根結點的右子樹的中序序列。而先序序列根結點後面分別為它的左子樹和右子樹的先序序列。有了根結點在中序序列的位置,就知道了左子樹和右子樹的先序序列各自的位置。這樣,就知道了根結點兩個子樹的序列。
然後在構造了根結點後,就可以遞迴調用函數來勾結根結點的左子樹和右子樹。
以上為二叉樹的恢複。
後序遍曆二叉樹也是用遞迴即可。
代碼如下:
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;}