题解 | 二叉排序树

二叉排序树

https://www.nowcoder.com/practice/30a0153649304645935c949df7599602

#include <iostream>
using namespace std;
typedef struct btree{
  struct btree *left;
  struct btree *right;
  int data;
}btree;
int ans;
btree *insert(btree *t,int x)
{
   if(t==NULL)
   {
    t=new btree;
    t->left=t->right=NULL;
    t->data=x;
    ans=-1;
   }
   if(x>t->data)
   {
     int f=(t->right==NULL);
     t->right=insert(t->right,x);
     if(f&&t->right!=NULL)
     ans=t->data;
   }
   if(x<t->data)
   {
     int f=(t->left==NULL);
     t->left=insert(t->left,x);
     if(f&&t->left!=NULL)
     ans=t->data;
   }
   return t;
}
int main() {
  int n;cin>>n;
   btree *t=NULL;
  while(n--)
  {
    int x;cin>>x;
    t=insert(t,x);
    cout<<ans<<endl;
  }
}

全部评论

相关推荐

06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务