二叉树非递归遍历

来源:互联网 发布:淘宝试用成功怎么领取 编辑:程序博客网 时间:2024/05/23 11:00
#include<iostream>#include<stack>#include<queue>using namespace std;typedef struct bintree{char data;struct bintree *leftchild;struct bintree *rightchild;}BinTree;BinTree* Node(char data,BinTree *leftchild,BinTree *rightchild);BinTree* build_tree(void);int preorder_traverse(BinTree * const root);int inorder_traverse(BinTree * const root);int postorder_traverse(BinTree * const root);int levelorder_traverse(BinTree * const root);int main(){   BinTree *root=NULL;if(!(root=build_tree())){cerr<<"build tree failed!"<<endl;return -1;}preorder_traverse(root);inorder_traverse(root);postorder_traverse(root);levelorder_traverse(root);return 0;}int preorder_traverse(BinTree * const root){if(NULL==root){cerr<<"tree is not exit"<<endl;return -1;}stack<BinTree*> s;    BinTree *p=root;/*naive thoughtaction1:while(p){cout<<p->data<<endl;    s.push(p);p=p->leftchild;}action2:if(s.empty())return 0;p=s.top();s.pop();if(p->rightchild!=NULL){    p=p->rightchild;goto action1;}else    {   goto action2;}然后写得漂亮一点*/while(p  || !s.empty()){if(p){cout<<p->data<<endl;s.push(p);p=p->leftchild;}else{p=s.top();s.pop();p=p->rightchild;}}return 0;}int inorder_traverse(BinTree * const root){if(NULL==root){cerr<<"tree is not exit"<<endl;return -1;}stack<BinTree*> s;    BinTree *p=root;while(p  || !s.empty()){if(p){s.push(p);p=p->leftchild;}else{p=s.top();s.pop();cout<<p->data<<endl;p=p->rightchild;}}return 0;}int postorder_traverse(BinTree * const root){if(NULL==root){cerr<<"tree is not exit"<<endl;return -1;}stack<BinTree*> s;    BinTree *p=root;BinTree *flag=NULL;while(p  || !s.empty()){if(p){s.push(p);p=p->leftchild;}else{if(s.top()->rightchild != flag){p=s.top()->rightchild;flag=NULL;}else{flag=s.top();s.pop();cout<<flag->data<<endl;}}}return 0;}int levelorder_traverse(BinTree * const root){if(!root) { return -1;}queue<BinTree *> q;BinTree *p=root;q.push(p);while(!q.empty()){p=q.front();q.pop();cout<<p->data<<endl;if(p->leftchild) { q.push(p->leftchild);}if(p->rightchild) { q.push(p->rightchild);}}return 0;}BinTree* build_tree(void){BinTree *d=Node('D',0,0);BinTree *g=Node('G',0,0);BinTree *h=Node('H',0,0);BinTree *i=Node('I',0,0);BinTree *b=Node('B',d,0);BinTree *e=Node('E',g,h);BinTree *f=Node('F',0,i);BinTree *c=Node('C',e,f);BinTree *a=Node('A',b,c);return a;}BinTree* Node(char data,BinTree *leftchild,BinTree *rightchild){BinTree *p=new BinTree;p->data=data;p->leftchild=leftchild;p->rightchild=rightchild;return p;}

0 0
原创粉丝点击