二叉树的先序非递归遍历

#include <stdio.h>
#include <stdlib.h>
#define bj 0
typedef struct node_2{
int value;
struct node_2 *left_child;
struct node_2 *right_child;
}BinaryTree;


typedef struct node {
BinaryTree *value;
struct node *next;
}stack;

typedef struct node_1{
int count;
stack *top;
}Stack;

、、栈的初始化
void Stack_init(Stack **p){
*p=(Stack*)malloc(sizeof(Stack));
(*p)->count=0;
(*p)->top=NULL;
}

。。入栈
void Stack_push(Stack *p,BinaryTree* date){
if(p==NULL)  return ;
stack *u=NULL;
u=(stack*)malloc(sizeof(stack));
u->value=date;
u->next=p->top;
p->top=u;
p->count++;
}

。。出栈
BinaryTree* Stack_pop(Stack *p){
if(p==NULL|| p->top==NULL)  return NULL;
BinaryTree *u=NULL;

stack *t=NULL;
t=p->top;

u=t->value;
p->top=p->top->next;
free(t);
t=NULL;
p->count--;
return u;
}

。。先序递归创建二叉树
void create_BinaryTree(BinaryTree **p){
int date;
scanf("%d",&date);
if(date==bj)  return ;
*p=(BinaryTree*)malloc(sizeof(BinaryTree));
(*p)->value=date;
(*p)->left_child=NULL;
(*p)->right_child=NULL;
create_BinaryTree(&(*p)->left_child);
create_BinaryTree(&(*p)->right_child);
}



、、创建普通二叉树
BinaryTree* create_1(){
BinaryTree *p=NULL;
p=(BinaryTree*)malloc(sizeof(BinaryTree));
p->value=1;

p->left_child=(BinaryTree*)malloc(sizeof(BinaryTree));
p->left_child->value=2;

p->left_child->left_child=(BinaryTree*)malloc(sizeof(BinaryTree));
p->left_child->left_child->value=4;
p->left_child->left_child->left_child=NULL;
p->left_child->left_child->right_child=NULL;


p->left_child->right_child=(BinaryTree*)malloc(sizeof(BinaryTree));
p->left_child->right_child->value=5;
p->left_child->right_child->left_child=NULL;
p->left_child->right_child->right_child=NULL;
    
    p->right_child=(BinaryTree*)malloc(sizeof(BinaryTree));
p->right_child->value=3;

p->right_child->left_child=(BinaryTree*)malloc(sizeof(BinaryTree));
p->right_child->left_child->value=6;
p->right_child->left_child->left_child=NULL;
p->right_child->left_child->right_child=NULL;

p->right_child->right_child=NULL;

return p;
}

。。二叉树的线序遍历
void Pretraver(BinaryTree *p){
if(p==NULL)  return ;
printf("%d ",p->value);
Pretraver(p->left_child);
Pretraver(p->right_child);
}

二叉树先序遍历的非递归遍历方式

思路:进入循环while(1)  依次进行遍历给二叉树的左子树  直到找到最后的一个节点是空的时候退出内层循环

          每次取出栈顶的元素  当弹出的结果的右孩子不是空的时候  再次进入内层的循环中依次查找新的子树的左孩子

          推出大循环的条件是 当从栈中弹出的元素为空的时候 当最后弹出栈的结果是空的时候  结束整个遍历过程

void nice(BinaryTree *pTree)
{
if(pTree == NULL)return;
Stack *pStack = NULL;
Stack_init(&pStack);
while(1)
{
while(pTree)
{
printf("%d ",pTree->value);
Stack_push(pStack,pTree);
pTree = pTree->left_child;
}
pTree = Stack_pop(pStack);
if(pTree == NULL)break;
pTree = pTree->right_child;
}
}
int main()
{
BinaryTree *p=NULL;
create_BinaryTree(&p);
Pretraver(p);
printf("\n***************************************************\n");
BinaryTree *q=NULL;
q=create_1();
nice(q);
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42211587/article/details/80890447