先序遍历与中序遍历的代码实现是差不多的 只是把访问节点的操作放到了入栈操作前
代码实现:
#include <stdio.h> #include <string.h> #include <stdlib.h> #define ElementType char int top = -1; //定义top栈顶元素下标 // 结点结构体 typedef struct BinTNode { ElementType data; struct BinTNode *left; struct BinTNode *right; } BinTNode, *BinTree; // 初始化树形结构 BinTNode *CreateBiTree(BinTNode *T) { T = (BinTNode *)malloc(sizeof(BinTNode)); T->data = 'A'; T->left = (BinTNode *)malloc(sizeof(BinTNode)); T->left->data = 'B'; T->right = (BinTNode *)malloc(sizeof(BinTNode)); T->right->data = 'C'; T->left->left = (BinTNode *)malloc(sizeof(BinTNode)); T->left->left->data = 'D'; T->left->right = (BinTNode *)malloc(sizeof(BinTNode)); T->left->right->data = 'E'; T->left->right->left = NULL; T->left->right->right = NULL; T->left->left->left = (BinTNode *)malloc(sizeof(BinTNode)); T->left->left->left->data = 'H'; T->left->left->left->left = NULL; T->left->left->left->right = NULL; T->left->left->right = (BinTNode *)malloc(sizeof(BinTNode)); T->left->left->right->data = 'I'; T->left->left->right->left = NULL; T->left->left->right->right = NULL; T->right->left = (BinTNode *)malloc(sizeof(BinTNode)); T->right->left->data = 'F'; T->right->left->left = NULL; T->right->left->right = NULL; T->right->right = (BinTNode *)malloc(sizeof(BinTNode)); T->right->right->data = 'G'; T->right->right->left = NULL; T->right->right->right = NULL; return T; } // 栈 - 进栈push void push(BinTNode **stack, BinTNode *elem) { stack[++top] = elem; } //栈 - 弹栈pop void pop() { if (top == -1) { return; } top--; } // 遍历过程中,输出结点值 void printElement(BinTNode *elem) { printf("%c ", elem->data); } //获取栈顶元素 BinTNode *getTop(BinTNode **stack) { return stack[top]; } //非递归遍历 - 左根右 void InOrderTraverse(BinTNode *Tree) { BinTNode *stack[20]; // 定义一个栈 BinTNode *p = Tree; // 定义临时指针 // 1 当前指针指向不为NULL - 说明有右孩子 // 2 或者栈内不空 - 说明该指针处没有右孩子,继续弹出结点值 while (p || top != -1) { while (p) { printElement(p); push(stack, p); // 循环将左孩子进栈 p = p->left; } if (top != -1) { p = getTop(stack); //取栈顶元素 pop(); //栈顶元素弹栈 p = p->right; } } } int main() { BinTNode *Tree; Tree = CreateBiTree(Tree); printf("先序遍历: "); InOrderTraverse(Tree); printf(" "); return 0; }
输出: