二叉树遍历的c语言非递归实现
来源:互联网 发布:linux rpm位置 编辑:程序博客网 时间:2024/05/17 04:48
/*二叉树的前序,中序,后序非递归遍历,stack表示树的节点栈,此处实现省略*/#include <stdio.h>#include "Tree.h"#include "Stack.h"//前序非递归void PreOrder_tree(Tree T){ Stack s; Node temp = T; while(!isEmpty(s) || temp!=NULL) { if(temp != NULL) { printf("%d ",temp); push(s,temp); temp = temp->left; } else { Node tem = pop(s); temp = tem->right; } }}//中序非递归void MidOrder_tree(Tree T){ Stack s; Node temp = T; while(!isEmpty(s) || temp!=NULL) { if(temp != NULL) { push(s,temp); temp = temp->left; } else { Node tem = pop(s); printf("%d ",temp); temp = tem->right; } }}//后序非递归void PostOrder_tree(Tree T){ Stack s; Node pre = NULL; //进行判断的辅助节点,表示前驱 Node temp = T; while(!isEmpty(s) || temp!=NULL) { if(temp != NULL) { push(s,temp); temp = temp->left; } else { if(Top(s)->right == pre || Top(s)->right == NULL) { printf("%d ",Top(s)->Elment); pre = pop(s); temp = NULL; } else temp = Top(s)->right; } }}