forked from PhuocQuang76/Homework-10
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree.h
96 lines (83 loc) · 1.72 KB
/
Tree.h
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
//
// Created by Sangalang, Emmanuel on 5/10/18.
//
#ifndef PROJECT10_BINARYTREE_H
#define PROJECT10_BINARYTREE_H
#include "WordList.h"
#include "TreeNode.h"
template <class T>
class Tree
{
// Internal class which stores only Node related information.
//public:
// struct TreeNode
// : public TreeNode {
//
// };
private:
void freeMemory(TreeNode<T> *);
public:
TreeNode<T> *root;
Tree();
~Tree();
T *insert(T *);
void print();
};
template <class T>
Tree<T>::Tree():root(NULL){
}
template <class T>
Tree<T>::~Tree()
{
freeMemory(root);
}
template <class T>
void Tree<T>::freeMemory(TreeNode <T> *node)
{
if (node==NULL)
return;
if (node->left)
freeMemory(node->left);
if (root->right)
freeMemory(node->right);
delete node;
}
template <class T>
//make it return value?
T *Tree<T>::insert(T *val)
{
TreeNode<T> *treeNode = NULL;
try
{
treeNode = new TreeNode<T>();
treeNode->data = val;
} catch (std::bad_alloc &exception)
{
std::cerr << "bad_alloc caught: " << exception.what() << std::endl;
EXIT_FAILURE;
}
TreeNode<T> *temp=NULL;
TreeNode<T> *prev=NULL;
temp = root;
while(temp)
{
prev = temp;
if (*temp->data == *treeNode->data)
return temp->data;
else if (*temp->data < *treeNode->data)
temp = temp->right;
else
temp = temp->left;
}
if (prev==NULL)
root = treeNode;
else
{
if (*prev->data<*treeNode->data)
prev->right = treeNode; // use setter function?
else
prev->left = treeNode;
}
return treeNode->data;
}
#endif //PROJECT10_BINARYTREE_H