赞
踩
#include <bits/stdc++.h> using namespace std; int post[50] , ino[50]; //定义全局变量 typedef struct btnode { int data; struct btnode *lchild,*rchild; }btnode , *btree; btree buildetree(int root,int start,int end);//root为后序根节点,start为中序开始,end为中序结尾 void DLRtree(btree bt); int main(){ btree bt; int N; cin>>N; int i; for(i=0;i<N;i++){ int x; cin>>x; post[i] = x; } for(i=0;i<N;i++){ int x; cin>>x; ino[i] = x; } bt = buildetree(N-1,0,N-1);//root在第N-1个位置,start开始在0位置,end在第N-1个位置 cout<<"Preorder:"; DLRtree(bt); return 0; } btree buildetree(int root,int start,int end){ if(start>end) return 0; btree bt; int i; for(i=start;post[root] !=ino[i];i++); bt = new btnode; bt->data = post[root]; bt->lchild = buildetree(root-(end-i)-1,start,i-1); bt->rchild = buildetree(root-1,i+1,end); //下面图片 return bt; } void DLRtree(btree bt){ if(bt == NULL) return; cout<<" "<<bt->data ; DLRtree(bt->lchild ); DLRtree(bt->rchild ); } 
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。