今天早上写的二叉树的建立及遍历


//树的操作
#include<malloc.h>
#include<iostream>
#include<string>
#define MAXN 100
using namespace std;

typedef struct node
{
  char data;
  struct node *left,*right;
}BTree;

int create_tree(BTree *&b,string str)
{
  b=NULL;
  BTree *p;
  int k;  //k表示左或右孩子树
  char c;
  int top=-1;
  BTree *stack[MAXN];
  int j=0;
  c=str[j];
  while(c!='/0')
    {
    switch(c)
      {

      case '(':top++;k=1;stack[top]=p;break;
      case ',':k=2;break;
      case ')':top--;break;
      default:
        p=(BTree *)malloc(sizeof(BTree));
        p->left=p->right=NULL;
        p->data=str[j];
    if(b==NULL)
      {
        b=p;
      }
    else
      {
        switch(k)
          {
          case 1:stack[top]->left=p;break;
          case 2:stack[top]->right=p;break;
          }
      }
      }
    j++;
    c=str[j];
    }
  return 1;
}
void inorder(BTree *b)
{
  if(b!=NULL)
    {

inorder(b->left);
  cout<<b->data<<" ";
inorder(b->right);
    }

}
void porder(BTree *b)
{
  BTree *stack[MAXN],*p;
  int top;
  if(b!=NULL)
    {
    top=1;
    stack[top]=b;
    while(top>0)
      {
    p=stack[top];
    top--;
    cout<<p->data<<" ";
    if(p->right!=NULL)
      {
            top++;
        stack[top]=p->right;
     
      }
    if(p->left!=NULL)
      {
            top++;
        stack[top]=p->left;
     
      }
   
      }
    }
}
void inorder_s(BTree *b)
{
  BTree *stack[MAXN];
  int top=-1;
  if(b!=NULL)
    {
      while(b->left!=NULL)
    {
      top++;
      stack[top]=b->left;
      b=b->left;
    }

      while(top>=0)
    {
      cout<<stack[top]->data<<" ";
      top--;

    }
      while(b->right!=NULL)
    {
      top++;
      stack[top]=b->right;
      b=b->right;
    }
      while(top>=0)
    {
      cout<<stack[top]->data<<" ";
      top--;
    }
    }
}
void postorder(BTree *b)
{
  if(b!=NULL)
    {
      postorder(b->left);
      postorder(b->right);
      cout<<b->data<<" ";
    }

}
int main()
{
  BTree *b;
  create_tree(b,"a(b(c),d(e(,f),g))");
  inorder(b);
  cout<<endl;
  postorder(b);
  cout<<endl;
  inorder_s(b);
  cout<<endl;
  porder(b);
  cout<<endl;
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值