您的位置:首页 > 其它

递归和非递归俩种方法实现二叉树的前序遍历

2013-04-09 15:28 691 查看
#include<iostream>
using namsapce std;
typedef struct BiNode
{
struct BiNode* lchild;
struct BiNode* rchild;
char data;
}BiNode,*BiTree;
递归:

void preOrder(BiTree root)
{
if(NULL==root)
return ;
cout<<root->data<<" ";
preOrder(root->lchild);
preOrder(root->rchild);
}
非递归:

void preOrder2(BiTree root)
{
if(NULL==root)
return ;
stack<BiNode*> s;
BiNode* p = root;
cout<<p->data<<" ";
s.push(p);
while(p->lchild)
{
cout<<p->lchild->data<<" ";
s.push(p->lchild);
p = p->lchild;
}
while(!s.empty())
{
p = s.top();
s.pop();
BiNode *q = p->rchild;
while(q!=NULL)
{
cout<<q->data<<" ";
q = q->lchild;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐