#include <iostream> #include <stack> #include <queue> //#include <aa.h> using namespace std; struct BiTreeNode { int data; BiTreeNode *lchild; BiTreeNode *rchild; bool flag; BiTreeNode() { data = 0; lchild = NULL; rchild = NULL; flag = false; } }; typedef BiTreeNode* BiTree; BiTree createTree() { BiTree t; BiTree a[10]; for(int i = 0; i < 7; i++) { a[i] = new BiTreeNode(); a[i]->data = i; } t = a[0]; for(int j = 2; j >= 0; j--) { a[j]->lchild = a[2*j+1]; a[j]->rchild = a[2*j+2]; } return t; } void visit(BiTree t) { cout<<t->data<<" "; } void PreOrder(BiTree T) { stack<BiTree> s; s.push(T); BiTree t; while(!s.empty()) { t = s.top(); s.pop(); visit(t); if(t->rchild) s.push(t->rchild); if(t->lchild) s.push(t->lchild); } } void InOrder(BiTree T) { stack<BiTree> s; s.push(T); BiTree t; while(!s.empty()) { t = s.top(); s.pop(); if(t->flag) visit(t); else { if(t->rchild) s.push(t->rchild); t->flag = true; s.push(t); if(t->lchild) s.push(t->lchild); } } } void PostOrder(BiTree T) { stack<BiTree> s; s.push(T); BiTree t; while(!s.empty()) { t = s.top(); s.pop(); if(t->flag) visit(t); else { t->flag = true; s.push(t); if(t->rchild) s.push(t->rchild); if(t->lchild) s.push(t->lchild); } } } void LayerOrder(BiTree T) { queue<BiTree> q; q.push(T); BiTree t; while(!q.empty()) { t = q.front(); q.pop(); visit(t); if(t->lchild) q.push(t->lchild); if(t->rchild) q.push(t->rchild); } } int main() { BiTreeNode *T1 = NULL, *T2 = NULL, *T3 = NULL; T1 = createTree(); T3 = createTree(); T2 = createTree(); cout<<"后序遍历:"<<endl; PostOrder(T1); cout<<endl; cout<<"先序遍历:"<<endl; PreOrder(T2); cout<<endl; cout<<"中序遍历:"<<endl; InOrder(T3); cout<<endl; cout<<"层次遍历:"<<endl; LayerOrder(T3); cout<<endl; return 0; }