数据结构之二叉树的中序非递归遍历

二叉树的中序非递归遍历

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<stack>
#define ElemType int
#define maxsize 100
using namespace std;

typedef struct BiNode{
    ElemType data;
    struct BiNode* lchild;
    struct BiNode* rchild;
}BiNode,*BiTree;
int num=0;
 ElemType arr[19]={1,2,4,8,0,0,9,0,0,5,0,0,3,6,0,0,7,0,0};

//----------------二叉树的建立--------------------
BiTree Creat()
{
    ElemType x;
    BiTree bt;
    x=*(arr+num);
    num++;
    if(x==0)
        bt=NULL;
    else if(x>0)
    {
        bt=(BiNode*)malloc(sizeof(BiNode));
        bt->data=x;
        bt->lchild=Creat();
        bt->rchild=Creat();
    }
    else
        printf("输入错误\n");
    return bt;
}

//----------------中序非递归遍历二叉树---------------
void  InOrderwithoutRecursion(BiTree bt)
{
    if(bt==NULL)   //空树返回
    {
        printf("空树!\n");
        return ;
    }
    stack<BiNode*> s;
    //树非空
    BiTree p=bt;
    BiNode* q;
    while(p!=NULL||!s.empty())
    {
        if(p)
        {

            s.push(p);
            //GetStack(s);
            p=p->lchild;
        }
        else
        {
           // printf("else ");
            q=s.top();
            printf("%d ",q->data);
            s.pop();
            p=q->rchild;
        }
    }   //while
}
//----------------中序递归遍历二叉树-----------------
void InOrderTraverse(BiTree bt)
{
    if(bt)
    {
        InOrderTraverse(bt->lchild);
        printf("%d ",bt->data);
        InOrderTraverse(bt->rchild);
    }
}

//-----------------中序非递归遍历二叉树-----------------

int main()
{
    BiTree bt=Creat();
    printf("这是递归遍历!\n");
    InOrderTraverse(bt);
    printf("\n这是非递归遍历!\n");
    InOrderwithoutRecursion(bt);
}

这里写图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值