双栈法对二叉树进行层序遍历
所谓二叉树的层序遍历就是对二叉树的按从上到下的层序在每一层按从左到右的顺序输出数据元素
二叉树的结构
typedef struct BinaryTree
{
char data;
struct BinaryTree* lchild;//左孩子
struct BinaryTree* rchild;//右孩子
}BinaryTree,*Bitree;
层序遍历代码
void flow_traverse(Bitree T)//层序遍历
{
stack<Bitree>s1,s2;//定义两个栈
Bitree p = T;
cout << p->data;
s1.push(p->rchild);
s1.push(p->lchild);//将根结点的左右孩子压入栈1
while (1)
{
if (s1.empty() && s2.empty())//循环结束条件
break;
while(!s2.empty())
{
if (s2.top()->rchild != NULL)
s1.push(s2.top()->rchild);
if(s2.top()->lchild != NULL)
s1.push(s2.top()->lchild);
s2.pop();
}
while (!s1.empty())
{
cout << s1.top()->data;
s2.push(s1.top());
s1.pop();
}
}
}
感谢你的阅读!