#include<bits/stdc++.h>
using namespace std;
struct Node{
int key;
Node *right,*left,*parent;
};
Node *root,*NIL;
void insert(int k){
Node *x=root;
Node *y =NULL;
Node *z=(Node *)malloc(sizeof(Node));
z->key=k;z->left=NULL;z->right=NULL;
while(x!=NULL){
y=x;
if(x->key>z->key){
x=x->left;
}
else x=x->right;
}
z->parent=y;
if(y==NULL)root=z;
else {
if(y->key>z->key){
y->left=z;
}
else y->right=z;
}
}
Node * find(Node *u,int k){
while(u!=NULL&&u->key!=k){
if(u->key>k)u=u->left;
else u=u->right;
}
return u;
}
void inorder(Node *u){
if(u==NIL)return ;
inorder(u->left);
printf(" %d",u->key);
inorder(u->right);
}
void preorder(Node *u){
if(u==NIL)return ;
printf(" %d",u->key);
preorder(u->left);
preorder(u->right);
}
int main(){
int n,i,x,k;
string com;
scanf("%d",&n);
for(int i=0;i<n;i++){
cin>>com;
if(com=="insert"){
scanf("%d",&x);
insert(x);
}else if(com=="print"){
inorder(root);
printf("\n");
preorder(root);
printf("\n");
}
else if(com=="find"){
scanf("%d",&k);
if(find(root,k)!=NULL)printf("yes\n");
else printf("no\n");
}
}
} ```
ALDS1_8_B 二叉树的搜索
最新推荐文章于 2020-12-02 22:27:32 发布