核心思想:根节点和左孩子直接遍历,若有右孩子,则入栈。没有左右孩子,直接出栈顶元素。
#ifndef _BTREE_H_
#define _BTREE_H_
typedef char BTDataType;
typedef struct BinaryTreeNode{
BTDataType data;
struct BinaryTreeNode* lchild;
struct BinaryTreeNode* rchild;
}BTNode;
void BinaryTreeDestory(BTNode* root);
void BinaryTreePrevOrderNonR(BTNode* root);
#endif/*_BTREE_H_*/
// 顺序表的动态存储 栈用顺序表实现
#ifndef _Stack_H_
#define _Stack_H_
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "BTree.h"
typedef BTNode * StDataType;
typedef struct Stack {
StDataType* array; // 指向动态开辟的数组
size_t size; // 有效数据个数
size_t capicity; // 容量空间的大小
}Stack;
// 基本增删查改接口
void StackInit(Stack* psl, size_t capacity);
void StackDestory(Stack* psl);
void StackPush(Stack* psl, StDataType x);
void StackPop(Stack* psl);
StDataType StackTop(Stack* psl);
int StackIsEmpty(Stack* psl);
#endif //_Stack_H_
// 顺序表的动态存储 栈用顺序表实现
#ifndef _Stack_H_
#define _Stack_H_
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "BTree.h"
typedef BTNode * StDataType;
typedef struct Stack {
StDataType* array; // 指向动态开辟的数组
size_t size; // 有效数据个数
size_t capicity; // 容量空间的大小
}Stack;
// 基本增删查改接口
void StackInit(Stack* psl, size_t capacity);
void StackDestory(Stack* psl);
void StackPush(Stack* psl, StDataType x);
void StackPop(Stack* psl);
StDataType StackTop(Stack* psl);
int StackIsEmpty(Stack* psl);
#endif //_Stack_H_
#include"BTree.h"
#include"stack.h"
#include<stdio.h>
#include<stdlib.h>
void BinaryTreePrevOrderNonR(BTNode* root)//用非递归(栈)实现前序遍历
{
Stack st;
BTNode *cur = root;//root是根节点
StackInit(&st,100);
while (cur)
{
putchar(cur->data);
if (cur->rchild)//前序遍历右孩子入栈
{
StackPush(&st, cur->rchild);
}
if (cur->lchild)//直接遍历左孩子
{
cur = cur->lchild;
}
else
{
cur = StackTop(&st);
StackPop(&st);//没有左右孩子,直接出栈顶元素
}
}
StackDestory(&st);
}
#include "BTree.h"
#include "queue.h"
#include "stack.h"
int main()
{
BTNode * root = BinaryTreeCreate("ABD#GI##J###CE#HK###F##");
BinaryTreePrevOrderNonR(root);
putchar('\n');
BinaryTreeDestory(root);
system("pause");
return 0;
}