143-3 二叉树后序非递归遍历
二叉树的后序非递归遍历
使用辅助栈
r指针的作用是判断该结点是否遍历过
#include <stdio.h> #include <stdlib.h> #define MaxSize 20 typedef struct node{ int data; struct node *lchild,*rchild; }TreeNode,*Tree; typedef TreeNode* Elem; typedef struct{ TreeNode* data[MaxSize]; int top; }Stack; void InitStack(Stack &S) { S.top=-1; } bool isEmpty(Stack S) { if(S.top==-1) return true; else return false; } bool isFull(Stack S) { if(S.top==MaxSize-1) return true; else return false; } bool Push(Stack &S,Elem x) { if(isFull(S)) return false; S.data[++S.top]=x; return true; } bool Pop(Stack &S,Elem &x) { if(isEmpty(S)) return false; x=S.data[S.top--]; return true; } bool GetTop(Stack S,Elem &x) { if(isEmpty(S)) return false; x=S.data[S.top]; return true; } void CreateTree(Tree &T) { int x; scanf("%d",&x); if(x==-1) { T=NULL; return; } else { T=(TreeNode*)malloc(sizeof(TreeNode)); T->data=x; printf("输入%d的左结点:",x); CreateTree(T->lchild); printf("输入%d的右结点:",x); CreateTree(T->rchild); } } void LatOrderTree(Tree T) { Stack S; InitStack(S); TreeNode *p=T; TreeNode *r=NULL; while(p || !isEmpty(S)) { if(p) { Push(S,p); p=p->lchild; } else { GetTop(S,p); if(p->rchild&&p->rchild!=r) { p=p->rchild; } else { Pop(S,p); printf("%d ",p->data); r=p; p=NULL; } } } } int main() { Tree T; CreateTree(T); LatOrderTree(T); return 0; }