使用扩展先序遍历二叉树来进行二叉树的创建,使用非递归方法遍历二叉树,并且不同于书上使用的顺序栈,这里采用链栈,与顺序栈的不同是不能将NULL压栈,因此算法较复杂一些,是一次尝试。
C语言代码:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//定义二叉树
typedef struct BinaryTree{
char data;
BinaryTree *leftChild;
BinaryTree *rightChild;
int f;
}BinaryTree,*PBinaryTree;
//定义一个栈
typedef struct Stack{
PBinaryTree data;
Stack *next;
}Stack,*PStack;
//初始化栈
void initStack(PStack x){
x->data=NULL;
x->next=NULL;
}
//判空
int empty(PStack x){
if(x->next==NULL)
return 1;
return 0;
}
//入栈
void push(PStack x,PBinaryTree d){
PStack newNode=(PStack)malloc(sizeof(Stack));
if(!newNode)
exit(0);
newNode->data=d;
newNode->next=x->next;
x->next=newNode;
}
//出栈
PBinaryTree pop(PStack x){
if(empty(x))
return NULL;
PBinaryTree pop=x->next->data;
PStack popNode=x->next;
x->next=popNode->next;
free(popNode);
return pop;
}
//释放栈
void delStack(PStack x){
while(!empty(x))
pop(x);
free(x);
}
//扩充的先序遍历二叉树创建树
void createTree(PBinaryTree &root){
char x;
scanf("%c",&x);
if(x=='.')
root=NULL;
else{
root=(PBinaryTree)malloc(sizeof(BinaryTree));
if(!root)
exit(0);
root->data=x;
root->f=0;
createTree(root->leftChild);
createTree(root->rightChild);
}
}
//后序遍历二叉树
int orderTree(PBinaryTree root){
if(root){
PStack s=(PStack)malloc(sizeof(Stack));
if(!s)
exit(0);
initStack(s);
push(s,root);
PBinaryTree p=s->next->data;
while(!empty(s)){
while(p->leftChild!=NULL&&p->leftChild->f==0){
push(s,p->leftChild);
p=s->next->data;
}
if(p->rightChild!=NULL&&p->rightChild->f==0){
push(s,p->rightChild);
p=s->next->data;
}
if((p->leftChild==NULL||p->leftChild->f==1)&&(p->rightChild==NULL||p->rightChild->f==1)){
printf("%2c",p->data);
p->f=1;
pop(s);
if(s->next==NULL)
p=NULL;
else
p=s->next->data;
}
}
return 0;
}
else
return 1;
}
int main(){
PBinaryTree myTree;
printf("请按扩展先序遍历创建二叉树:\n");
createTree(myTree);
orderTree(myTree);
return 0;
}