-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.cpp
137 lines (107 loc) · 3.16 KB
/
tree.cpp
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <iostream>
#include <string>
#include <regex>
#include "tree.h"
#include "node.cpp"
using namespace std;
Node* Tree::getNode(Node* root, string data) {
if (root != NULL) {
if (root->data == data) {
return root;
} else {
Node *v = getNode(root->left, data);
if (v != NULL) {
return v;
} else {
Node *v = getNode(root->right, data);
if (v != NULL) {
return v;
} else {
return NULL;
}
}
}
} else {
return NULL;
}
}
//===================================================
void Tree::addElememt(string line){
regex e ("(.+)(l|r)(.+)");
smatch m;
if (regex_search(line, m, e)) { //valid input
string a = m[1];
string b = m[3];
string choice = m[2];
//b is child of a
Node *parent = getNode(root, a);
Node *child = getNode(root, b);
if (parent == NULL) {
//cout<< "parent is null"<<endl;
parent = new Node(a);
//the new root is parent
if (root != NULL) {
//parent->left = root;
root = parent;
//cout<< "root has changed"<<endl;
}
}
if (child == NULL) {
//cout<< "child is null"<<endl;
child = new Node(b);
}
//put o left or right
if (choice == "l") {
//cout<<"put on left"<<endl;
parent->left = child;
} else {
//cout<<"put on right"<<endl;
parent->right = child;
}
if(root == NULL){
//cout<< "root is null"<<endl;
root = parent;
}
} else {
cout<<"invalid input : "<<line<<endl;
}
}
/* The function Compute the "height" of a tree. Height is the number of
nodes along the longest path from the root node down to the farthest leaf node.*/
int Tree::height(Node* node){
/* base case tree is empty */
if (node == NULL)
return 0;
//height = 1 + max of left height and right heights
return 1 + max(height(node->left), height(node->right));
}
//================================
/* function return true if tree is balanced */
bool Tree::isBalanced(){
return isBalanced(root);
}
bool Tree::isBalanced(Node* root){
//the empty tree is balanced
if (root == NULL) {
return true;
}
cout <<"Checking node "<<root->data<<"..."<<endl;
int leftHeight = height(root->left); // height of left subtree
int rightHeight = height(root->right); // height of right subtree
int d = abs(leftHeight - rightHeight);
if (d <= 1 && isBalanced(root->left) && isBalanced(root->right)) {
return true;
} else {
return false;
}
}
void Tree::print() {
print(root);
}
void Tree::print(Node* root) {
if (root != NULL) {
print(root->left);
cout<<root->data<<endl;
print(root->right);
}
}