二叉树的非递归遍历(迭代遍历)
通过栈来实现
初始化
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char data;
struct TreeNode* lchild;
struct TreeNode* rchild;
int flag;//用于后序遍历判断右子树是否被访问过
}
typedef struct StackNode {
TreeNode* data;
struct StackNode* next;
} StackNode;
void createTree(TreeNode* T, char* data, int* index) {
char ch;
ch = data[*index];
*index += 1;
if (ch == '#') {
*T = NULL;
} else {
*T = (TreeeNode*)malloc(sizeof(TreeNode));
(*T) -> data = ch;
(*T) -> flag = 0;
createTree(&((*T) -> lchild), data, index);
createTree(&((*T) -> lchild), data, index);
}
}
StackNode* initStack() {
StackNode* S = (StackNode*)malloc(sizeof(StackNode));
S -> data= NULL;
S -> next = NULL;
return S;
}
void push(TreeNode* data, StackNode* S) {
StackNode* node = (StackNode*)malloc(sizeof(StackNode));
node -> data = dat;
node -> next = S -> next;
S -> next = node;
}
int isEmpty(StackNode* S) {
if (S -> next = NULL) {
return 1;
} else {
return 0;
}
}
StackNode* pop(StackNode* S) {
if (isEmpty(S)) {
return NULL;
} else {
StackNode* node = S -> next;
S -> next = node -> next;
return node;
}
}
StackNode* getTop(StackNode* S) {
if (isEmpty(S)) {
return NULL;
} else {
StackNode* node = S -> next;
return node;
}
}//用于后序遍历中拿到当前子树的根节点
int main(int argc, char* argv[]) {
TreeNode* T;
int index = 0;
createTree(&T, argv[1], &index);
preOrder(T);
inOrder(T);
return 0;
}
中序遍历
左根右:DBEAFCG
按照左根右顺序,有则入栈,无则出栈
实现:
- 入栈根节点
- 循环,直到左孩子为空
- 出栈,访问节点,入栈右孩子
void inOrder(TreeNode* T) {
TreeNode* node = T;
StackNode* S = initStack():
while(node || !isEmpty(S)) {
if (node) {
push(node, S);
node = node -> lchild;
} else {
node = pop(S) -> data;
printf("%c ", node -> data);
node = node -> rchlid;
}
}
}
前序遍历
根左右:ABDECFG
按照根左右顺序,有则入栈,无则出栈
实现:
- 入栈根节点
- 循环,直到根节点为空
- 出栈,访问节点,入栈右孩子
void preOrder(TreeNdoe* T) {
TreeNode* node = T;
StackNode* S = initStack();
while (node || !isEmpty(S)) {
if (node) {
printf("%c", node -> data);
push(node, S);
node = node -> lchild
} else {
node = pop(S) -> data;
node = node -> rchild;
}
}
}
后序遍历
左右根:DEBFGCA
- 从根节点开始,寻找最左边的节点,并依次入栈
- 出栈前,判断栈顶元素是否还有右子树。如果有,判断右子树是否被访问过。若已访问过,则回到上一个节点,若未访问过,则将右子树入栈。若没有右子树了,则出栈。
void postOrder(TreeNode* T) {
TreeNode* node = T;
StackNode* S= initStack();
while (node || !isEmpty(S)) {
if (node) {
push(node, S);
node = node -> lchild;
} else {
TreNode* top = getTop(S) -> data;
if (top -> rchild && top -> rchild -> flag == 0) {
top = top -> rchild;
push(top, S);
node = top -> lchild
} else {
top = pop(S) -> data;
printf("C ", top -> data);
top -> falg = 1;
}
}
}
}