#include <bits/stdc++.h>
#include <vector>
#include <map>
#define x first
#define y second
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define sz(v) size(v)
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
const int N = 510;
typedef struct Tree
{
int data;
struct Tree *lchild;
struct Tree *rchild;
}Tree, *BitTree;
BitTree stk[N];
BitTree que[N];
int tt, tt1, tt2;
int front, rear = -1;
BitTree create() //二叉树的创建
{
int op;
BitTree t;
scanf("%d", &op);
if(op == -1) return NULL;
t = (BitTree)malloc(sizeof(Tree));
t->data = op;
printf("请输入%d的左子树:", op);
t->lchild = create();
printf("请输入%d的右子树:", op);
t->rchild = create();
return t;
}
//二叉树的递归遍历
void xianxu(BitTree t) //先序遍历
{
if(t == NULL) return;
printf("%d", t->data);
xianxu(t->lchild);
xianxu(t->rchild);
}
void houxu(BitTree t) //后续遍历
{
if(t == NULL) return;
houxu(t->lchild);
houxu(t->rchild);
printf("%d", t->data);
}
void zhongxu(BitTree t) //中序遍历
{
if(t == NULL) return;
zhongxu(t->lchild); //递归遍历左子树
printf("%d", t->data);
zhongxu(t->rchild); //递归遍历右子树
}
//二叉树的非递归遍历
void xianxu2(BitTree t) //压入栈的顺序为右左根
{
if(t == NULL) return;
stk[++tt] = t;
while(tt > 0)
{
BitTree temp = stk[tt--];
printf("%d\n", temp->data);
if(temp->rchild != NULL) stk[++tt] = temp->rchild;
if(temp->lchild != NULL) stk[++tt] = temp->lchild;
}
}
void zhongxu2(BitTree t)
{
if(t == NULL) return;
BitTree temp = t;
while(tt > 0 || temp != NULL)
{
if(temp != NULL)
{
stk[++tt] = temp;
temp = temp->lchild;
}
else
{
temp = stk[tt--];
printf("%d\n", temp->data);
temp = temp->rchild;
}
}
}
void houxu2(BitTree t)
{
if(t == NULL) return;
BitTree stk1[N];
BitTree stk2[N];
stk1[++tt1] = t;
while(tt1 > 0)
{
BitTree temp = stk1[tt1--];
stk2[++tt2] = temp;
if(temp->lchild != NULL) stk1[++tt1] = temp->lchild;
if(temp->rchild != NULL) stk1[++tt1] = temp->rchild;
}
while(tt2 > 0)
{
printf("%d\n", stk2[tt2--]->data);
}
}
//二叉树的层序遍历
void cengxu2(BitTree t)
{
if(t == NULL) return;
que[++rear] = t;
while(front <= rear)
{
BitTree temp = que[front++];
printf("%d ", temp->data);
if (temp->lchild != NULL)
{
que[++rear] = temp->lchild;
}
if (temp->rchild != NULL)
{
que[++rear] = temp->rchild;
}
}
}
int main()
{
BitTree t = create();
return 0;
}
二叉树的遍历(递归与非递归)
最新推荐文章于 2024-09-26 22:55:54 发布