您的位置:首页 > 编程语言 > C语言/C++

C++先,中,后顺序遍历的非递归实现

2015-11-24 14:03 411 查看
二叉树是一种非常重要的数据结构,很多其他数据机构都是基于二叉树的基础演变过来的。二叉树有前、中、后三种遍历方式,因为树的本身就是用递归定义的,因此采用递归的方法实现三种遍历,不仅代码简洁且容易理解,但其开销也比较大,而若采用非递归方法实现三种遍历,则要用栈来模拟实现(递归也是用栈实现的)。下面详细介绍三种遍历方式的非递归实现。

先创建树节点

struct tree //创建树节点

{

int data;

tree*left,*right;

};

根据先序遍历的顺序,先访问根节点,再访问左子树,后访问右子树,而对于每个子树来说,又按照同样的访问顺序进行遍历。

void preorder(tree*temp)//先序遍历非递归实现
{
stack<tree*>s;
if(temp==NULL)
return ;
s.push(temp);
tree*p;
while(!s.empty())
{
while(p=s.top())
{
cout<<p->data<<" ";
s.push(p->left);
}
s.pop();
if(!s.empty())
{
p=s.top();
s.pop();
s.push(p->right);
}
}
}
void inorder(tree*temp)//中序遍历非递归实现
{
stack<tree*>s;
if(temp==NULL)
return ;
s.push(temp);
tree*p;
while(!s.empty())
{
while(p=s.top())
{
s.push(p->left);
}
s.pop();
if(!s.empty())
{
p=s.top();
s.pop();
cout<<p->data<<" ";
s.push(p->right);
}
}
}


void postorder(tree*temp)//后序遍历非递归实现
{
stack<tree*>s;
if(temp==NULL)
return ;
s.push(temp);
tree*p;
while(!s.empty())
{
while(p=s.top())
{
s.push(p->left);
}
s.pop();
if(!s.empty())
{
p=s.top();
s.pop();
s.push(p->right);
cout<<p->data<<" ";
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: