二叉树中序遍历非递归算法.

#include <iostream>
using namespace std;

struct Node
{
 struct Node *leftchild;
 struct Node *rightchild;
 int data;
};

 

struct Node *root = NULL;


void create_search_tree(int element)
{
 struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
 temp->data = element;
 temp->leftchild = temp->rightchild = NULL;
 if(root==NULL)
 {
  root = temp;
  return;
 }
 struct Node *pre , *current = root;
 while(current!=NULL)
 {
  pre = current;
  if(element>current->data)
  {
   current = current->rightchild;
  }
  else
  {
   current = current->leftchild;
  }
 }
 if(element>pre->data)
 {
  pre->rightchild = temp;
 }
 else
 {
  pre->rightchild = temp;
 }
}

 

//定义一个简单的数组栈

static struct Node* arr[200];
int top = -1;

 

void push(struct Node *element)
{
 if(top+1==200)
 {
  return;
 }
 top++;
 arr[top] = element;
}

void pop(struct Node **element)
{
 if(top==-1)
 {
  return;
 }
 *element = arr[top];
 top--;
}

bool is_empty()
{
 return top ==-1;
}

 

 

//中根遍历一棵树,当中根遍历一棵二叉搜树时,会得到一个有序序列.
void midorder(struct Node *root)
{
 struct Node *p = root;
 while(!is_empty()||p!=NULL)
 {
      if(p!=NULL)
     {
            push(p);
            p = p->leftchild;
      }

      else
     {
           pop(&p);
           cout<<p->data<<"  ";
           p = p->rightchild;
      }
  }
}

 

 

int main()
{
 int arr[16] = {12,2,1,45,23,18,67,89,9,43,65,78,67,13,24,52};
 for(int i=0; i<16; i++)
 {
  create_search_tree(i);
 } 
 midorder(root);
 cout<<endl;
 return 0;
}

void preorder(struct Node *root)

{ //先根遍历 struct Node *p = root;

while(p!=NULL || !is_empty())

 //只要这两者有一个条件还不萍踪就执行.

{ if(p==NULL) { pop(&p); }

cout<data<<" "; if(p->rightchild!=NULL)

{ push(p->rightchild); }

 p = p->leftchild; } }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值