二叉树作为一个应用广泛的数据结构,是程序员必须掌握的结构之一。
在此记录之前学习时写出的实现及操作,以备不时之需。
目录
头文件及二叉树结构体
#include<stdio.h>
#include<malloc.h>
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
typedef struct bt
{
char data;
struct bt *lchild,*rchild;
}bt,*bitree;
二叉树的创建
int create(bitree &t)
{
char ch;
scanf("%c",&ch);
if(ch==' ') t=NULL;
else
{
if(!(t=(bitree)malloc(sizeof(bt)))) return 0;
t->data=ch;
create(t->lchild);
create(t->rchild);
}
return 1;
}
先序、中序、后序遍历二叉树(递归)
void pot(bitree &t) /*先序遍历二叉树*/
{
if(t) printf("%c ",t->data);
if(t->lchild) pot(t->lchild);
if(t->rchild) pot(t->rchild);
}
void iot(bitree &t) /*中序遍历二叉树*/
{
if(t)
{
if(t->lchild) iot(t->lchild);
printf("%c ",t->data);
if(t->rchild) iot(t->rchild);
}
}
void lot(bitree &t) /*后序遍历二叉树*/
{
if(t)
{ if(t->lchild)
lot(t->lchild);
if(t->rchild)
lot(t->rchild);
printf("%c ",t->data);
}
}
层序遍历(非递归)
void cot(bitree &t) /*层序遍历二叉树*/
{
if(t)
{queue<bitree>q;
q.push(t);
while(!q.empty())
{
bitree p=q.front();
q.pop();
printf("%c ",p->data);
if(p->lchild) q.push(p->lchild);
if(p->rchild) q.push(p->rchild);
}
}
}
先序、中序、后序遍历二叉树(非递归)
void fpot(bitree &t)
{
if(!t)
return ;
stack<bitree>s;
s.push(t);
while(!s.empty())
{
bitree p=s.top();
printf("%c ",p->data);
s.pop();
if(p->rchild) s.push(p->rchild );
if(p->lchild) s.push(p->lchild );
}
}
void fiot(bitree &t)
{
stack<bitree>s;
bitree p=t;
while(p||!s.empty())
{
if(p)
{
s.push(p);
p=p->lchild;
}
else
{
p=s.top();
printf("%c ",p->data);
s.pop();
p=p->rchild ;
}
}
}
void flot(bitree &t)
{
stack<bitree>s;
bitree p=NULL,flag;
s.push(t);
while(!s.empty())
{
flag=s.top();
if((flag->lchild==NULL&&flag->rchild==NULL)||(p!=NULL&&(p==flag->lchild||p==flag->rchild)))
{
s.pop();
printf("%c ",flag->data);
p=flag;
}
else
{
if(flag->rchild) s.push(flag->rchild);
if(flag->lchild) s.push(flag->lchild);
}
}
}
测试代码
void main()
{
bitree t;
create(t);
printf("递归:\n");
printf("前序:");pot(t);printf("\n");
printf("中序:");iot(t);printf("\n");
printf("后序:");lot(t);printf("\n");
printf("非递归:\n");
printf("层序:");cot(t);printf("\n");
printf("前序:");fpot(t);printf("\n");
printf("中序:");fiot(t);printf("\n");
printf("后序:");flot(t);printf("\n");
}
代码改变生活。