forked from sysprog21/phonebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phonebook_bst.c
60 lines (54 loc) · 1.24 KB
/
phonebook_bst.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
59
60
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include "phonebook_bst.h"
/* FILL YOUR OWN IMPLEMENTATION HERE! */
bst *findName(char lastName[], bst* root)
{
bst* temp = root;
while (temp != NULL) {
int val = strcasecmp(lastName, temp->lastName);
if(val == 0)
return temp;
temp = (val < 0) ? temp->left : temp->right;
}
return NULL;
}
entry *append(char lastName[], entry *e)
{
e->pNext = (entry *) malloc(sizeof(entry));
e = e->pNext;
strcpy(e->lastName, lastName);
e->pNext = NULL;
return e;
}
bst *list_to_BST(entry *pHead)
{
int listLen = 0;
entry *cur = pHead;
while(cur) {
listLen++;
cur = cur->pNext;
}
return build(&pHead, listLen);
}
bst *build(entry **pHead, int listLen)
{
if(listLen <= 0)
return NULL;
bst *left = build(pHead, listLen/2);
bst *root = (bst *) malloc(sizeof(bst));
strcpy(root->lastName, (*pHead)->lastName);
root->left = left;
*pHead = (*pHead)->pNext;
root->right = build(pHead, listLen-listLen/2-1);
return root;
}
void releaseTree(bst *root)
{
if(root == NULL) return;
releaseTree(root->left);
releaseTree(root->right);
free(root);
}