-
Notifications
You must be signed in to change notification settings - Fork 0
/
hackerank1.cpp
122 lines (111 loc) · 2.5 KB
/
hackerank1.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
#include <iostream>
#include <cstddef>
#include<stdlib.h>
using namespace std;
class Node{
public:
int data;
Node *left;
Node *right;
Node(int d){
data = d;
left = NULL;
right = NULL;
}
};
class Solution{
public:
Node* insert(Node* root, int data) {
if(root == NULL) {
return new Node(data);
}
else {
Node* cur;
if(data <= root->data){
cur = insert(root->left, data);
root->left = cur;
}
else{
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
} struct qnd{
Node* nd;
struct qnd* next;
};
typedef struct qnd qnd;
void enqueue(qnd** frref,qnd** reref,Node* data)
{
qnd* newnode=(qnd*)malloc(sizeof(qnd));
newnode->nd=data;
newnode->next=NULL;
if((*frref)==NULL&&(*reref)==NULL)
{
(*frref)=(*reref)=newnode;
return;
}
(*reref)->next=newnode;
(*reref)=newnode;
}
void dequeue(qnd** frref,qnd** reref)
{
qnd* temp=(*frref);
if((*frref)==NULL)
{return;
}
else if((*frref)==(*reref))
{
(*frref)=(*reref)=NULL;
free(temp);
return;
}
(*frref)=(*frref)->next;
free(temp);
}
bool isempty(qnd* frref)
{
if(frref==NULL)return true;
else return false;
}
int BFStrvsl(Node* root)
{ int n=0;
qnd* front=NULL;
qnd* rear=NULL;
if(root==NULL)
return 0;
enqueue(&front,&rear,root);
while(!isempty(front))
{
Node* current=front->nd;
n++;
if(current->left!=NULL)enqueue(&front,&rear,current->left);
if(current->right!=NULL)enqueue(&front,&rear,current->right);
dequeue(&front,&rear);
}
return n;
}
int getHeight(Node* root){
int height=0;
int node=BFStrvsl(root);
for(int i=node;i/2!=0;i=i/2)
height++;
return height;
//Write your code here
}
}; //End of Solution
int main() {
Solution myTree;
Node* root = NULL;
int t;
int data;
cin >> t;
while(t-- > 0){
cin >> data;
root = myTree.insert(root, data);
}
int height = myTree.getHeight(root);
cout << height;
return 0;
}