二叉树的基本操作
本篇主要包括二叉树的创建,前序遍历,中序遍历,后序遍历等基本操作 。。。更基础的知识就不在这里赘述了。
二叉树的创建
由于是通过链式结构存储的,先定义二叉树的链式结构体。
typedef struct BiTNode
{
int data;
struct BiTNode* lchild;
struct BiTNode* rchild;
} BITNODE,*BITree
**struct BiTNode =BITNODE; 意思是用BITNODE 代替struct BiTNode
struct BiTNode* =BITree; 意思是用BITree 代替struct BiTNode***
定义一个空的二叉树
BITree tree = NULL;
只有根的二叉树
BiTree root = (BiTree) malloc(sizeof(BiTNODE));
root->data= 6;
root->lchild = NULL;
root->rchild = NULL;
二叉树的遍历
先序遍历的递归算法
所有子树都是按照 根结点 ->左子树 ->右子树 的顺序操作。(根左右)
//前序遍历
void PreO(BITree T)
{
if(T){
printf("%d",T->data);
PreO(T->lchild);
PreO(T->rchild);
}
}
中序遍历的递归算法
所有子树都是按照 左子树 ->根结点 ->右子树 的顺序操作。(左根右)
//中序遍历
void MidO(BITree T)
{
if(T){
MidO(T->lchild);
printf("%d",T->data);
MidO(T->rchild);
}
}
后序遍历的递归算法
所有子树都是按照 左子树 ->右结点 ->根结点 的顺序操作。(左根右)
//后序遍历:
void LastO(BITree T)
{
if(T){
LastO(T->lchild);
LastO(T->rchild);
printf("%c",T->data);
}
}
对比上面的三个递归运算后会发现其实大同小异,主要区别在于什么时候打印,先序遍历是在第一次遍历到的时候就打印,中序遍历是在第二次打印,后序遍历是第三次才打印。
二叉树的非递归遍历
先序遍历(非递归)
void PreOByStack(BITree T)
{
if(!T)
return;
BITree p = T;
BITree stack[100];
int stacktop = -1;
while(stacktop != -1|| p)
{
//先走到最左下角 边走边打印
while(p){
printf("%c",p->data);
stack[++stacktop] = p;
p = p->lchild;
}
if(stacktop != -1)
{
p = stack[stacktop--]; //出栈操作
p = p->rchild;
}
}
}
中序遍历(非递归)
void MidOByStack(BITree T)
{
if(!T)
return;
BITree p = T;
BITree stack[100];
int stacktop = -1;
while(stacktop != -1|| p)
{
//先走到左下角 走的时候不打印
while(p){
//printf("%c",p->data);
stack[++stacktop] = p; //入栈操作
p = p->lchild;
}
//回来的时候 再打印
if(stacktop != -1)
{
p = stack[stacktop--]; //出栈操作
printf("%c",p->data);
p = p->rchild;
}
}
}
#include<stdio.h>
#include<stdlib.h>
int main()
{
BITree tree;
printf("请输入数据:\n");
Crebypre(&tree);
printf("先序遍历:\n");
PreO(tree);
printf("\n");
printf("中序遍历:\n");
MidO(tree);
printf("\n");
printf("后序遍历:\n");
LastO(tree);
printf("\n");
printf("非递归先序遍历:\n");
PreOByStack(tree);
printf("\n");
printf("非递归中序遍历:\n");
MidOByStack(tree);
return 0;
}