3种递归遍历
前序遍历(中->左->右)
void Pre(Tree *root){
if(root){
Visit(root->data); //printf
Pre(root->lchild);
Pre(root->rchild);
}
}
中序遍历(左->中->右)
void In(Tree *root){
if(root){
In(root->lchild);
Visit(root->data); //printf
In(root->rchild);
}
}
后序遍历(左->右->中)
void Post(Tree *root){
if(root){
Post(root->lchild);
Post(root->rchild);
Visit(root->data); //printf
}
}
3种非递归遍历
前序遍历
void Pre2(Tree *root){
Stack s;
Tree *cur=root;
Tree *top=NULL;
if(root==NULL) return ;
Init(&s);
while(cur || !StackEmpty(&s)){
while(cur){
Visit(cur->data);
Push(&s,cur);
cur=cur->lchild;
}
top=StackTop(&s);
Pop(&s);
cur=top->rchild;
}
}
中序遍历
void In2(Tree *root){
Stack s;
Tree *cur=root;
Tree *top=NULL;
if(root==NULL) return ;
Init(&s);
while(cur || !StackEmpty(&s)){
while(cur){
Push(&s,cur);
cur=cur->lchild;
}
top=StackTop(&s);
Visit(cur->data);
Pop(&s);
cur=top->rchild;
}
}
后序遍历
void Post2(Tree *root){
Stack s;
Tree *cur=root;
Tree *top=NULL;
Tree *prev=NULL;
if(root==NULL) return ;
Init(&s);
while(cur || !StackEmpty(&s)){
while(cur){
Push(&s,cur);
cur=cur->lchild;
}
top=StackTop(&s);
if(top->rchild==NULL || top->rchild==prev){
Visit(top->data);
prev=top;
Pop(&s);
}
else{
cur=top->rchild;
}
}
}
谢谢浏览;