-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree.h
110 lines (88 loc) · 2.77 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//--------------------------------------------------------------------------------------------------------------------------------
// Hassan Shahzad & Azka Khurram
// 18i-0441 & 18i-0461
// Algo-Project
// FAST NUCES
// Tree.h
//--------------------------------------------------------------------------------------------------------------------------------
//================================================================================================================================
// 1: This file contains a Tree data structure with all its functionalities and some adjusted according to our requirements
//================================================================================================================================
#pragma once
#include "Queue.h"
class Tree {
public:
node* root;
private:
void destroySubTree(node* nodee) {
if (nodee != NULL) {
destroySubTree(nodee->left);
destroySubTree(nodee->right);
delete nodee;
nodee = NULL;
}
}
void inOrder(node* root) {
if (root != NULL) {
inOrder(root->left);
cout << "| " << root->data << " | " << root->freq << "\t|" << endl;
cout << " ----------------------- " << endl;
inOrder(root->right);
}
}
void encodingTree(node* root, string str, int n, char charArray[], string stringArray[]) // recursively finds the bit strings for every symbol in the tree
{
if (root == nullptr)
return;
// found a leaf node
if (!root->left && !root->right) {
int index=0;
for (int i = 0; i < n; i++) {
if (charArray[i] == root->data) {
index = i;
break;
}
}
stringArray[index] = str;
}
encodingTree(root->left, str + "0", n, charArray, stringArray);
encodingTree(root->right, str + "1", n, charArray, stringArray);
}
void copyTreeToSelf(node*& copiedTreeRoot, node* otherTreeRoot) // copying second tree to the first
{
if (otherTreeRoot == NULL)
copiedTreeRoot = NULL;
else
{
copiedTreeRoot = new node;
copiedTreeRoot->data = otherTreeRoot->data;
copiedTreeRoot->freq = otherTreeRoot->freq;
copyTreeToSelf(copiedTreeRoot->left, otherTreeRoot->left);
copyTreeToSelf(copiedTreeRoot->right, otherTreeRoot->right);
}
}
public:
Tree() {
root = NULL;
}
~Tree()
{
this->destroySubTree(root);
}
void displayPostOrder()
{
cout << " ----------------------- " << endl;
cout << " Node | Freq " << endl;
cout << " ----------------------- " << endl;
this->inOrder(root);
}
void copyTree(node* otherTreeRoot)
{
this->copyTreeToSelf(root, otherTreeRoot);
}
void encode(int n, char charArray[], string stringArray[])
{
string str;
this->encodingTree(root, str, n, charArray, stringArray);
}
};