-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.c
99 lines (79 loc) · 2.31 KB
/
tree.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"
#include "heaps.h"
//----------------------------------------------------------------
//-------------------------------------------- Creating A New Node
Node* newNode(char* word,float value)
{
Node* n=malloc(sizeof(Node));
n->name=malloc(strlen(word)+1);
strcpy(n->name,word);
n->value=value;
n->left=n->right=NULL;
return n;
}
//----------------------------------------------------------------
//---------------------------------------- Insert Node To The Tree
Node* insert(Node* Root,char* key,float value){
if(Root==NULL)
return newNode(key,value);
Node *n=search(Root,key);
if(n)
n->value=value;
else if(strcasecmp(key,Root->name) > 0)
Root->right=insert(Root->right, key,value);
else
Root->left=insert(Root->left, key,value);
return Root;
}
//----------------------------------------------------------------
//---------------------------------------- Search Through The tree
Node* search(Node* root, char* key)
{
if(!root||!key)
return NULL;
else if (strcasecmp(key,root->name)==0)
return root;
else if (strcasecmp(key,root->name)<0) {
return search((Node *) root->left, key);
}
else{
return search((Node *) root->right, key);
}
}
//----------------------------------------------------------------
//---------------------------------------------- InOrder Traversal
void inOrder(Node* root)
{
if(root)
{
inOrder((Node *) root->left);
printf("%s = %.2f\n", root->name, root->value);
inOrder((Node *) root->right);
}
}
int count(Node* root)
{
if(root==NULL)
return 0;
else
return 1+count(root->left)+count(root->right);
}
//----------------------------------------------------------------
//-----------------------------------------Copy the tree into heap
void fromTreeToHeap(Node * root,variable heap[])
{
if(root)
{
static int heapIndex=0;
fromTreeToHeap((Node *) root->left,heap);
heap[heapIndex].value=root->value;
heap[heapIndex].name=malloc(strlen(root->name)+1);
strcpy(heap[heapIndex].name,root->name);
heapifyUp(heap,heapIndex);
++heapIndex;
fromTreeToHeap((Node *) root->right,heap);
}
}