考二叉搜索树的插入。
#include<iostream>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
typedef struct node tree;
int main(){
int n;
while(cin >> n){
tree* root=NULL;
while(n!=0){
int i ;
cin >> i;
if(!root){
cout << -1 <<'\n';
tree* tem=new tree ;
root=tem;
root->data=i;
root->left=NULL;
root->right=NULL;
}else{
tree* pre=root;
tree* now=root;
int tag=0;
while(now){
pre=now;
if(i>now->data){
now=now->right;
tag=1;
}else if(i<now->data){
now=now->left;
tag=0;
}
}
tree* tem= new tree ;
tem->data=i;
tem->left=NULL;
tem->right=NULL;
if(tag==0){
pre->left=tem;
}else{
pre->right=tem;
}
cout << pre->data <<'\n';
}
n--;
}
}
return 0;
}
结果:
标签:right,NULL,tem,KY207,tree,C++,二叉,now,root From: https://www.cnblogs.com/llllmz/p/17985838