二叉树遍历算法

      二叉树的遍历是个比较常用且经典的问题,它有递归和非递归的方式来实现三种遍历方式,递归的方式相对比较简单,这里主要用非递归的方式实现二叉树的三种遍历方式。

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值