#include <stdio.h>
#include <stdlib.h>
#define DATATYPE char
#define MAXSIZE 100
typedef struct node{
DATATYPE data;
struct node *lchild,*rchild;
}LINKBINTREE;
LINKBINTREE *create()
{
int num,father,j = 0;
LINKBINTREE *pArr[MAXSIZE],*p;
char s[] = "abcdefg\0";
while(s[j]!='\0'){
p = (LINKBINTREE*)malloc(sizeof(LINKBINTREE));
p->rchild = NULL;
p->lchild = NULL;
p->data = s[j++];
pArr[j] = p;
if(j!=1){
father = j/2;//父节点
if(j%2==0){
pArr[father]->lchild = p;//左子树
}else
pArr[father]->rchild = p;
}
}
return pArr[1];//返回根节点即可找到剩余的节点
}
void preOrderNoRecursion(LINKBINTREE *bTree)
{
// 非递归先序打印 ,根左右
int top = -1,isExit = 0;
LINKBINTREE *stack[100];
LINKBINTREE *p = bTree;
if(!bTree){
printf("bt is Empty!");
}else{
while(!isExit){
// 向bt进行左子树循环
while(p){
printf("%c",p->data);
stack[++top] = p;
p = p->lchild;
}
if(top==-1) isExit = 1;//栈到底了
else{
// 左子树循环完了,该出栈,然后循环右子树了
p = stack[top--];
p = p->rchild;
}
}
}
}
void midOrderNoRecursion(LINKBINTREE *bTree)
{
// 非递归中序遍历(左根右),利用栈的特性,若左子树不为空则继续向左子树循环,否则出栈打印
int top = -1,isExit = 0;
LINKBINTREE *stack[100];
LINKBINTREE *p = bTree;
if(!bTree){
printf("bt is Empty!");
}else{
while(!isExit){
// 向bt进行左子树循环
while(p){
stack[++top] = p;
p = p->lchild;
}
if(top==-1) isExit = 1;//栈到底了
else{
// 左子树循环完了,该出栈,然后循环右子树了
p = stack[top--];
printf("%c",p->data);
p = p->rchild;
}
}
}
}
typedef struct{
LINKBINTREE *p;
int tag;
}SNODE;
void postOrderNoRecursion(LINKBINTREE *bTree)
{
// 非递归后序打印 ,左右根
int top = -1,isExit = 0,tag;
SNODE stack[100];//切记这里不可以换成*stack[100],然后贪方便用->引用,否则出问题
SNODE snode;
LINKBINTREE *p = bTree;
if(!bTree){
printf("bt is Empty!");
}else{
while(!isExit){
// 向bt进行左子树循环
while(p){
snode.p = p;
snode.tag = 0;//遍历左子树,tag为0
stack[++top] = snode;
p = p->lchild;
}
if(top==-1) isExit = 1;//栈到底了
else{
snode = stack[top--];
p = snode.p;
tag = snode.tag;
if(tag==0){
// 遍历右子树
snode.p = p;
snode.tag = 1;
stack[++top] = snode;//入栈
p = p->rchild;
}else{
printf("%c",p->data);
p = NULL;
}
}
}
}
}
void level(LINKBINTREE *bTree)
{
// 层次遍历,即冲上往下按左到右遍历,利用队列容易实现
int front = 0,rear = 0;
LINKBINTREE *arr[MAXSIZE],*p;
if(bTree)
{
// 首节点入队
rear = (rear+1)%MAXSIZE;
arr[rear] = bTree;
}else{
printf("bt empty!");
return;
}
while(rear!=front){
// 当队列不为空时
front = (front+1)%MAXSIZE;
p = arr[front];//出队
printf("%c",p->data);
if(p->lchild)
{
// 左孩子入队
rear = (rear+1)%MAXSIZE;
arr[rear] = p->lchild;
}
if(p->rchild)
{
// 右孩子入队
rear = (rear+1)%MAXSIZE;
arr[rear] = p->rchild;
}
}
}
int main()
{
LINKBINTREE *bt = create();
postOrderNoRecursion(bt);
}
c语言:完全二叉树的非递归先、中、后序、层次遍历
最新推荐文章于 2022-08-06 17:01:52 发布