先序遍历
#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>
//树
typedef int ElemType;
typedef struct Node
{
struct Node *lchild;
ElemType data;
struct Node *rchild;
/* data */
}Node,Tree;
Tree * create_tree(Tree *t){
//先序创建
ElemType ch;
scanf("%d",&ch);
if(ch == 0)
//t = (Tree *)malloc(sizeof(Tree))
t = NULL;
else{
t = (Tree *)malloc(sizeof(Tree));
t->data = ch;
t->lchild = create_tree(t->lchild);
t->rchild = create_tree(t->rchild);
}
return t;
}
//栈
#define INIT_SIZE 10
#define INCREASE 10
typedef struct
{
Node *top;
Node *base;
int length;
int size;
/* data */
}Stack;
void init_stack(Stack *p){
p->base = p->top = (Node *)malloc(INIT_SIZE*sizeof(Node));
p->length = 0;
p->size = INIT_SIZE;
}
void push(Stack *p, Node *e){
if(p->length >= p->size){
p->base = (Node *)realloc(p->base,(p->size+INCREASE)*sizeof(Node));
p->top = p-> base + p->length;
p->size += INCREASE;
}
*p->top++ = *e;
p->length++;
}
Node * pop(Stack *p, Node *e){
if(p->top == p->base){
printf("THE STACK IS NULL");
return NULL;
}
e = --p->top;
p->length--;
return e;
}
bool Empty(Stack *stack){
if(stack->length == 0)
return true;
else return false;
}
void xianxu(Tree *t){
if(t == NULL){
return ;
}
Node *p = t;
Stack stack;
init_stack(&stack);
while(p || !Empty(&stack)){
while(p){
push(&stack,p);
p = p->lchild;
}
if(!Empty(&stack)){
p = pop(&stack,p);
printf("%2d",p->data);
p = p->rchild;
}
}
}
int main(){
Tree *t;
t = create_tree(t);
xianxu(t);
}
中序遍历
中序遍历与先序极其相似,只需要将访问放在入栈时即可
后续遍历
eg:这里将栈的该为静态存储,(因为我被指向指针的指针搞晕了)
#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>
//树
typedef int ElemType;
typedef struct Node
{
struct Node *lchild;
ElemType data;
struct Node *rchild;
/* data */
}Node,Tree;
Tree * create_tree(Tree *t){
//先序创建
ElemType ch;
scanf("%d",&ch);
if(ch == 0)
//t = (Tree *)malloc(sizeof(Tree))
t = NULL;
else{
t = (Tree *)malloc(sizeof(Tree));
t->data = ch;
t->lchild = create_tree(t->lchild);
t->rchild = create_tree(t->rchild);
}
return t;
}
//栈
#define INIT_SIZE 10
#define INCREASE 10
typedef struct
{
Node *Elem[10];
int top;
int base;
int length;
int size;
/* data */
}Stack;
void init_stack(Stack *p){
p->base = p->top = 0;
p->length = 0;
p->size = INIT_SIZE;
}
void push(Stack *p, Node *e){
if(p->length >= p->size){
printf("The Stack is Filled");
}
p->Elem[p->top] = e;
p->top++;
p->length++;
}
void pop(Stack *p){
if(p->top == p->base){
printf("THE STACK IS NULL");
return ;
}
Node *e = p->Elem[--p->top];
p->length--;
return ;
}
bool Empty(Stack *stack){
if(stack->length == 0)
return true;
else return false;
}
Node * top(Stack *p){
return p->Elem[p->top-1];
}
void houxu(Tree *t){
if(t == NULL){
return ;
}
Node *p = t;
Node *pre;
Stack stack;
init_stack(&stack);
while(p || !Empty(&stack)){
while(p){
push(&stack,p);
p = p->lchild;
}
p = top(&stack);
if( p->rchild == NULL || p->rchild == pre){
printf("%2d",p->data);
pop(&stack);
pre = p;
p = NULL;
}else{
p = p->rchild;
}
}
}
int main(){
Tree *t;
t = create_tree(t);
xianxu(t);
}