设有一棵满二叉树(所有结点值均不同),已知其先序序列为pre,设计一个算法求其后序序列post
#include <iostream>
#include <stack>
#include <queue>
#include<string.h>
typedef struct treenode{char data;struct treenode *left;struct treenode *right;
}treenode,*ptreenode;ptreenode buytreenode(char x)
{ptreenode n=(ptreenode) malloc(sizeof (treenode));n->data=x;n->left= nullptr,n->right= nullptr;return n;
}
ptreenode build_tree()
{ptreenode root= buytreenode('A');root->left= buytreenode('B');root->right= buytreenode('C');root->left->left= buytreenode('D');root->left->right= buytreenode('E');root->right->left= buytreenode('F');root->right->right= buytreenode('G');root->left->left->left= buytreenode('H');root->left->left->right= buytreenode('I');return root;
}ptreenode build_tree2()
{ptreenode root= buytreenode('A');root->left= buytreenode('B');root->right= buytreenode('C');root->left->left= buytreenode('D');root->left->right= buytreenode('E');root->right->left= buytreenode('F');root->right->right= buytreenode('G');root->left->left->left= buytreenode('H');root->left->left->right= buytreenode('I');root->left->right->left= buytreenode('J');root->left->right->right= buytreenode('K');root->right->left->left= buytreenode('L');root->right->left->right= buytreenode('M');root->right->right->left= buytreenode('N');root->right->right->right= buytreenode('O');return root;
}void print_tree(ptreenode root) {std::queue<ptreenode> tmp;tmp.push(root);int s = tmp.size();while (!tmp.empty()) {ptreenode t = tmp.front();tmp.pop();s--;printf("%3c", t->data);if (t->left) tmp.push(t->left);if (t->right) tmp.push(t->right);if (s == 0) puts(""), s = tmp.size();}
}void print_pre(ptreenode root)
{if(root== nullptr) return;printf("%3c",root->data);print_pre(root->left);print_pre(root->right);
}void print_post(ptreenode root)
{if(root== nullptr) return;;print_post(root->left);print_post(root->right);printf("%3c",root->data);
}void pre2post(char *pre,int l1,int h1,char* &post,int l2,int h2)
{int half;if(h1>=l1){post[h2]=pre[l1];half=(h1-l1)/2;pre2post(pre,l1+1,l1+half,post,l2,l2+half-1);pre2post(pre,l1+half+1,h1,post,l2+half,h2-1);}
}
void pretopost(char* record,int size)
{char *post=(char*) malloc(sizeof (char)*(size+1));memset(post,0,sizeof (char)*(size+1));pre2post(record,0,size,post,0,size);printf("our post order: ");for(int i=0;i<=size;i++) printf("%3c",post[i]);
}
int main() {ptreenode root=build_tree2();print_tree(root);puts("");printf("the pre order: ");print_pre(root);puts("");printf("the post order: ");print_post(root);puts("");char pre_record[]={"ABDHIEJKCFLMGNO"};pretopost(pre_record,14);return 0;
}