-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.c
58 lines (53 loc) · 1.15 KB
/
example.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
struct BSTNode
{
int data;
struct BSTNode* lchild;
struct BSTNode* rchild;
};
struct BSTNode* root=NULL;
struct BSTNode* createNode(int data);
struct BSTNode* insert(struct BSTNode* root,int data);;
void preOrder(struct BSTNode* root);
int main()
{
int data,i,n;
printf("Enter the size of BST : ");
scanf("%d\n",&n);
for(i=0;i<n;i++)
{
scanf("%d",&data);
root=insert(root,data);
}
printf("The preorder traversal is :\n");
preOrder(root);
return 0;
}
struct BSTNode* createNode(int data)
{
struct BSTNode* node=(struct BSTNode*)malloc(sizeof(struct BSTNode));
node->data=data;
node->lchild=node->rchild=NULL;
return node;
}
struct BSTNode* insert(struct BSTNode* root,int data)
{
if(root==NULL)
root= createNode(data);
else if(data<root->data)
root->lchild=insert(root->lchild,data);
else
root->rchild=insert(root->rchild,data);
return root;
}
void preOrder(struct BSTNode *ptr)
{
if(ptr==NULL)
{
return;
}
printf("%d ",ptr->data);
preOrder(ptr->lchild);
preOrder(ptr->rchild);
}