bintree cpp ifndef __BINTREE__ define __BINTREE__ include iostream tem

 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
// bintree.cpp
#ifndef __BINTREE__
#define __BINTREE__
#include <iostream>
template <class E>
class bintree {
int size;
struct node {
E data;
node *left, *right;
node(const E &x):data(x),right(NULL),left(NULL){}
};
node *root;
void _deleteNode(node*);
void _displayNode(node*, const char*);
public:
bintree():root(NULL),size(0){}
void push_back(const E&);
const E& find(const E&);
void display(const char* sep = "\n") {
_displayNode(root, sep);
}
~bintree() { _deleteNode(root); };
void sort();
};
template <class E>
void bintree<E>::push_back(const E& element) {
if(root == NULL) {
root = new node(element);
return;
}
node *parent, *now;
int dir; // 0 - left, 1 - right
now = root;
while(now != NULL) {
parent = now;
if(element < now->data) {
dir = 0;
now = now->left;
} else {
dir = 1;
now = now->right;
}
}
now = new node(element);
if(!dir) {
parent->left = now;
} else {
parent->right = now;
}
}
template <class E>
void bintree<E>::_deleteNode(node* element) {
if(element != NULL) {
_deleteNode(element->left);
_deleteNode(element->right);
delete element;
}
}
template <class E>
void bintree<E>::_displayNode(node* element, const char *str) {
if(element != NULL) {
_displayNode(element->left, str);
std::cout << element->data << str;
_displayNode(element->right, str);
}
}
template <class E>
const E& bintree<E>::find(const E& element) {
node* cnode = root;
while(cnode) {
if(cnode->data == element) {
return cnode->data;
}
if(element < cnode->data) {
cnode = cnode->left;
} else {
cnode = cnode->right;
}
}
throw "Unable to find element";
}
template <class E>
void bintree<E>::sort() {
// nothing happens
}
#endif