-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST_insert.cpp
63 lines (54 loc) · 963 Bytes
/
BST_insert.cpp
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
59
60
61
62
63
#include <iostream>
#include <cstdlib>
using namespace std;
int count;
typedef struct TreeNode
{
int key;
struct TreeNode* LChild;
struct TreeNode* RChild;
}node;
node* root = NULL;
node* treeSearch(node* root, int key)
{
if(root==NULL || root->key==key)
return root;
if(root->key > key)
return treeSearch(root->LChild, key);
else
return treeSearch(root->RChild, key);
}
node* treeInsert(node* root, int key)
{
if(root==NULL)
{
root = (node*)malloc(sizeof(node));
root->key = key;
root->LChild = NULL;
root->RChild = NULL; // root : new node
count++;
return root;
}
if(root->key > key)
{
root->LChild = treeInsert(root->LChild, key);
count++;
} else
{
root->RChild = treeInsert(root->RChild, key);
count++;
}
return root;
}
int main()
{
int size;
cin>>size;
for(int i=0; i<size; i++)
{
int n;
cin>>n;
root=treeInsert(root, n);
}
cout<<count<<endl;
}