Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- typedef struct node
- {
- int key;
- struct node *left;
- struct node *right;
- }node;
- node *creatnewnode(int key)
- {
- node *n=(node*)malloc(sizeof(node));
- n->left=NULL;n->right=NULL;
- n->key=key;
- return n;
- }
- node *insert(node *root,int key)
- {
- if(root==NULL){
- root=creatnewnode(key);
- return root;
- }
- else if(key<=root->key){
- root->left=insert(root->left,key);
- }
- else{
- root->right=insert(root->right,key);
- }
- return root;
- }
- void preorder(node *root)
- {
- if(root==NULL) return;
- printf("%d ",root->key);
- if(root->left!=NULL) preorder(root->left);
- if(root->right!=NULL) preorder(root->right);
- return;
- }
- void inorder(node *root)
- {
- if(root==NULL) return;
- if(root->left!=NULL) inorder(root->left);
- printf("%d ",root->key);
- if(root->right!=NULL) inorder(root->right);
- return;
- }
- void postorder(node *root)
- {
- if (root==NULL)return;
- if(root->left!=NULL) postorder(root->left);
- if(root->right!=NULL) postorder(root->right);
- printf("%d ",root->key);
- return;
- }
- node *bstsearch(node *temp,int key)
- {
- while(temp!=NULL){
- if(temp->key==key) return temp;
- if(key<=temp->key) temp=temp->left;
- else temp=temp->right;
- }
- return temp;
- }
- int main()
- {
- node *root=NULL;
- node *temp=NULL;
- root=insert(root,5);
- root=insert(root,3);
- root=insert(root,7);
- root=insert(root,9);
- root=insert(root,4);
- preorder(root);
- printf("\n");
- postorder(root);
- printf("\n");
- inorder(root);
- printf("\n");
- temp=bstsearch(root,5);
- if(temp==NULL) printf("there is no value\n");
- else printf("There it is %d\n",temp->key);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement