-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodeheight_challenge.cpp
88 lines (73 loc) · 1.58 KB
/
Nodeheight_challenge.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
class Node {
public:
int height; // to be set by computeHeight()
Node *left, *right;
Node() { height = -1; left = right = nullptr; }
~Node() {
delete left;
left = nullptr;
delete right;
right = nullptr;
}
};
void computeHeight(Node *n) {
if (n == nullptr) {
// base case
return;
}
else {
// right node call
computeHeight(n->right);
// left node call
computeHeight(n->left);
// define variables
Node *rn = n->right;
Node *ln = n->left;
// height zero leaf node
if (rn == nullptr && ln == nullptr) {
n->height = 0;
}
// else if only left subtree
else if (rn == nullptr && ln != nullptr) {
n->height = 1 + ln->height;
}
// else if only right subtree
else if (rn != nullptr && ln == nullptr) {
n->height = 1 + rn->height;
}
// else add deeper subtree
else {
if (rn->height >= ln->height) {
n->height = 1 + rn->height;
}
else {
n->height = 1 + ln->height;
}
}
return;
}
}
// This function prints the tree in a nested linear format.
void printTree(const Node *n) {
if (!n) return;
std::cout << n->height << "(";
printTree(n->left);
std::cout << ")(";
printTree(n->right);
std::cout << ")";
}
int main() {
Node *n = new Node();
n->left = new Node();
n->right = new Node();
n->right->left = new Node();
n->right->right = new Node();
n->right->right->right = new Node();
computeHeight(n);
printTree(n);
std::cout << std::endl << std::endl;
printTreeVertical(n);
delete n;
n = nullptr;
return 0;
}