准备考研时整理的代码。
一、树的定义
typedef struct BTNode{
char data;
struct BTNode *lchild,*rchild;
}BTNode,*BTree;
二、树的创建
BTNode* createTree(char tree[],int n,int nodenum){
BTNode *root=(BTNode*)malloc(sizeof(BTNode));
if (tree[n]!='0'){
root->data=tree[n];
}
else{
return NULL;
}
if(2*n+1<nodenum){
root->lchild=createTree(tree,2*n+1,nodenum);
}
if(2*n+2<nodenum){
root->rchild=createTree(tree,2*n+2,nodenum);
}
return root;
}
二、树的遍历
void preOrder_non_recursion(BTNode *T){ //先序非递归
BTNode *stack[MAXSIZE];
int top=-1;
BTNode *p;
if(T!=NULL){
stack[++top]=T;
while (top!=-1){
p=stack[top--];
cout<<p->data<<" ";
if(p->rchild!=NULL){
stack[++top]=p->rchild;
}
if(p->lchild!=NULL){
stack[++top]=p->lchild;
}
}
}
}
void inOrder_non_recursion(BTNode *T){ //中序非递归
BTNode *stack[MAXSIZE];
int top=-1;
BTNode *p=T;
while (p!=NULL||top!=-1){
if (p!=NULL){
stack[++top]=p;
p=p->lchild;
}
else{
p=stack[top--];
cout<<p->data<<" ";
p=p->rchild;
}
}
}
void postOrder_non_recursion(BTNode *T){ //后序非递归
BTNode *stack[MAXSIZE];
int top=-1;
BTNode *p=T,*r=NULL;
while (p!=NULL||top!=-1){
if(p!=NULL){
stack[++top]=p;
p=p->lchild;
}
else{
p=stack[top];
if(p->rchild!=NULL&&p->rchild!=r){
p=p->rchild;
stack[++top]=p;
p=p->lchild;
}
else{
top--; //出栈
cout<<p->data<<" ";
r=p;
p=NULL;
}
}
}
}
void ergodic_recursion(BTNode *T){
cout<<"PreOrder_non_recursion"<<endl;
preOrder_non_recursion(T);
cout<<endl;
cout<<"InOrder_non_recursion"<<endl;
inOrder_non_recursion(T);
cout<<endl;
cout<<"PostOrder_non_recursion"<<endl;
postOrder_non_recursion(T);
cout<<endl;
}
void preOrder_recursion(BTNode *T){ //先序递归
if(T==NULL)
return;
cout<<T->data<<" ";
preOrder_recursion(T->lchild);
preOrder_recursion(T->rchild);
}
void inOrder_recursion(BTNode *T){ //中序递归
if(T==NULL)
return;
inOrder_recursion(T->lchild);
cout<<T->data<<" ";
inOrder_recursion(T->rchild);
}
void postOrder_recursion(BTNode *T){ //后序递归
if(T==NULL)
return;
postOrder_recursion(T->lchild);
postOrder_recursion(T->rchild);
cout<<T->data<<" ";
}
void ergodic_non_recursion(BTNode *T){ //非递归遍历
cout<<"PreOrder_recursion"<<endl;
preOrder_recursion(T);
cout<<endl;
cout<<"InOrder_recursion"<<endl;
inOrder_recursion(T);
cout<<endl;
cout<<"PostOrder_recursion"<<endl;
postOrder_recursion(T);
cout<<endl;
}