根据先序中序建树
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define N 50using namespace std;int pre[N],in[N],post[N]; //存放先序,中序,后序的数组 int n;struct Node{int data;Node* lchild;Node* rchild;};Node* create(int prel,int prer,int inl,int inr) //根据先序和中序建立树 { //4个参数 先序的左右边界,中序的左右边界 if(prel>prer) //已经遍历完了,返回 {return NULL;}Node* root=new Node; //建立一个根结点,用来存放当前的树 root->data=pre[prel]; // 因为是已知先序,所以当前树的值,一定等于先序的最左边的点 int k; //记录当前根节点在中序的位置 for(k=inl;k<inr;k++) {if(in[k]==pre[prel]) //找到位置,跳出 break;}int numleft=k-inl; //当前树的左子树的大小 root->lchild=create(prel+1,prel+numleft,inl,k-1); //将这部分存入左子树 root->rchild=create(prel+numleft+1,prer,k+1,inr); // 将这部分存入右子树return root; //返回根结点的地址 }int num=0; //控制最后一个输出没有空格 void printfpost(Node* root) //后序输出 {if(root==NULL)return;printfpost(root->lchild);printfpost(root->rchild);printf("%d",root->data);num++;if(num<n) printf(" ");}int main(){scanf("%d",&n);for(int i=0;i<n;i++){scanf("%d",&pre[i]);}for(int i=0;i<n;i++){scanf("%d",&in[i]);}Node* root=create(0,n-1,0,n-1);printfpost(root);}样例输入:61 2 3 4 5 63 2 4 1 6 5输出3 4 2 6 5 1
根据后序中序建树
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <vector>#include <queue>#include <set>#define N 50using namespace std;int pre[N],in[N],post[N];int n;struct Node{int data;Node* lchild;Node* rchild;};Node* create(int postl,int postr,int inl,int inr){if(postl>postr){return NULL;}Node* root=new Node;root->data=post[postr];int k;for(k=inl;k<inr;k++){if(in[k]==post[postr])break;}int numleft=k-inl;root->lchild=create(postl,postl+numleft-1,inl,k-1);root->rchild=create(postl+numleft,postr-1,k+1,inr);return root;}void bfs(Node* root) //层次遍历输出 {queue<Node*> q;int num=0;q.push(root);while(!q.empty()){Node* now=q.front();q.pop();printf("%d",now->data);num++;if(num<n) printf(" ");if(now->lchild!=NULL) q.push(now->lchild);if(now->rchild!=NULL) q.push(now->rchild);}}int main(){scanf("%d",&n);for(int i=0;i<n;i++){scanf("%d",&post[i]);}for(int i=0;i<n;i++){scanf("%d",&in[i]);}Node* root=create(0,n-1,0,n-1);bfs(root);return 0;}样例输入:72 3 1 5 7 6 41 2 3 4 5 6 7输出4 1 6 3 5 7 2
0 0