二叉树的遍历(非递归)

来源:互联网 发布:淘宝客服工资有6000吗 编辑:程序博客网 时间:2024/05/16 14:58

二叉树的先序遍历

void preorder(Btree *root){Btree *p=root;stack<Btree*>s;while(p!=NULL||!s.empty()){while(p!=NULL){cout<<p->data<<" ";s.push(p);p=p->lchild;}if(!s.empty()){p=s.top();s.pop();p=p->rchild;}}}

二叉树的中序遍历

void inorder(Btree *root){Btree *p=root;stack<Btree*>s;while(p!=NULL||!s.empty()){while(p!=NULL){p=p->lchild;s.push(p);}if(!s.empty()){p=s.top();cout<<p->data<<" ";s.pop();p=p->rchild;}}}

二叉树的后序遍历

void postorder(Btree *root){Btree *p=root,*r=NULL,temp;stack<Btree*>s;while(p!=NULL||!s.empty()){if(p!=NULL){s.push(p);p=p->lchild;}else{p=s.top();if(p->rchild&&p->rchild!=r){p=p->rchild;s.push(p);p=p->lchild;}else{p=s.top();s.pop();cout<<p->data;r=p;p=NULL;}}}}

0 0
原创粉丝点击