二叉树的遍历是个比较常用且经典的问题,它有递归和非递归的方式来实现三种遍历方式,递归的方式相对比较简单,这里主要用非递归的方式实现二叉树的三种遍历方式。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
//节点结构体
struct node
{
char data;//数据域
node *left_child;//左孩子
node *right_child;//右孩子
};
//递归建树,应该传入一个二级指针,不然由于临时变量使得root退出函数后无效
void create_tree(node **root)
{
char data;
cin>>data;
if(data=='#')// 以#为结束标志
*root=NULL;
else
{
*root=new node;
(*root)->data=data;
cout<<"please input "<<data<<"'s left child:"<<endl;
create_tree(&(*root)->left_child);
cout<<"please input "<<data<<"'s right child:"<<endl;
create_tree(&(*root)->right_child);
}
}
//非递归先序遍历
void preOrder(node *root)
{
if(root==NULL)
return;
stack<node> result;
result.push(*root);
while(!result.empty())
{
node tem=result.top();
cout<<tem.data<<" ";
result.pop();
if(tem.right_child!=NULL)
result.push(*tem.right_child);//先保存右孩子
if(tem.left_child!=NULL)
result.push(*tem.left_child);//后保存左孩子
}
cout<<endl;
}
//非递归中序遍历
void inOrder(node *root)
{
if(root==NULL)
return;
stack<node> result;
result.push(*root);
while(!result.empty())
{
while(root!=NULL&&root->left_child!=NULL)
{
root=root->left_child;
result.push(*root);
}
node tem=result.top();
cout<<tem.data<<" ";
result.pop();
root=tem.right_child;
if(root!=NULL)
result.push(*root);
}
cout<<endl;
}
//非递归后序遍历,双栈法
void postOrder(node *root)
{
if(root==NULL)
return;
stack<node> tem;
stack<node> result;
tem.push(*root);
while(!tem.empty())
{
node t=tem.top();
tem.pop();
result.push(t);
if(t.left_child!=NULL)
tem.push(*(t.left_child));
if(t.right_child!=NULL)
tem.push(*(t.right_child));
}
while(!result.empty())
{
cout<<result.top().data<<" ";
result.pop();
}
cout<<endl;
}
int main()
{
node *root=NULL;
create_tree(&root);
preOrder(root);
inOrder(root);
postOrder(root);
return 0;
}