模拟了层次遍历的算法。
#include<iostream> #include<malloc.h> #include<queue> #include<list> using namespace std; struct node { char c; node *lchild,*rchild; }; char pre[100]; char mid[100]; void build(node* &t,int start1,int end1,int start2,int end2) { int i=start2; while(pre[start1]!=mid[i]) i=i+1; t=(node*)malloc(sizeof(node)); t->c=pre[start1]; if(i==start2) t->lchild=NULL; else build(t->lchild,start1+1,start1+i-start2,start2,i-1); if(i==end2) t->rchild=NULL; else build(t->rchild,start1+i-start2+1,end1,i+1,end2); } list<node*> que; list<node*> temp; void exchange(node *t) { if(!temp.empty()) temp.clear(); temp.push_back(t); while(!temp.empty()) { node* q; q=temp.front(); if(q->lchild) temp.push_back(q->lchild); if(q->rchild) temp.push_back(q->rchild); temp.pop_front(); node *r; r=q->lchild; q->lchild=q->rchild; q->rchild=r; } } void visit(node *t) { if(!que.empty()) que.clear(); que.push_back(t); while(!que.empty()) { node *x; x=que.front(); cout<<x->c; que.pop_front(); if(x->lchild) que.push_back(x->lchild); if(x->rchild) que.push_back(x->rchild); } } int main() { node *tree; int length; while(1==1) { cout<<"pre"<<endl; cin>>pre; cout<<"mid"<<endl; cin>>mid; length=strlen(mid); build(tree,0,length-1,0,length-1); exchange(tree); visit(tree); } return 0; }
将一棵二叉树的全部节点的左右子树交换顺序,布布扣,bubuko.com
原文:http://blog.csdn.net/killer_in_silence/article/details/23056601