数据结构 二叉搜索树实现

C++ 二叉搜索树实现

#include<cstdio>
#include<iostream>
using namespace std;

typedef struct Node
{
  int key;
  Node *left;
  Node *right;
}Node;

Node *t = new Node;

void Front(Node *p) //前序遍历
{
  printf("%d ",p->key);
  if(p->left) Front(p->left);
  if(p->right) Front(p->right);
}

void Mid(Node *p) //中序遍历
{
  if(p->left) Mid(p->left);
  printf("%d ",p->key);
  if(p->right) Mid(p->right);
}

void Back(Node *p) //后序遍历
{
  if(p->left)  Back(p->left);
  if(p->right) Back(p->right);
  printf("%d ",p->key);
}
//插入数据
Node* insert(Node *root,int key)
{
  if(!root)
  {
    Node *p = new Node;
    p->key = key;
    p->left =  p->right = NULL;
    return p;
  }
  else
  if(root->key > key) root->left = insert(root->left,key);
  else root->right = insert(root->right,key);
  return root;
}
//查找数据
bool search(Node *p,int x)
{
  if(!p) return false;
  else if(x == p->key) return true;
  else if(p->key > x) return search(p->left,x);
  else return search(p->right,x);
}


int main()
{
  int n,x;
  while(scanf("%d",&n)!=EOF)
  {
    t = NULL;
    for(int i = 0; i < n; i++)
    {
      scanf("%d",&x);
      t = insert(t,x);
    }
    Front(t);
    printf("\n");
    Mid(t);
    printf("\n");
    Back(t);
    printf("\n");
    cout<<search(t,115)<<endl;
  }
  return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值