Skip to content

Commit a5736b7

Browse files
Count max height of the binary tree
1 parent d3252e9 commit a5736b7

4 files changed

+85
-2
lines changed

count_max_height_of_a_binary_tree.cpp

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Node
5+
{
6+
public:
7+
int val;
8+
Node *left;
9+
Node *right;
10+
Node(int val)
11+
{
12+
this->val = val;
13+
this->left = NULL;
14+
this->right = NULL;
15+
}
16+
};
17+
18+
Node *input_binary_tree()
19+
{
20+
int val;
21+
cin >> val;
22+
23+
Node *root;
24+
25+
if (val == -1)
26+
root = NULL;
27+
else
28+
root = new Node(val);
29+
30+
queue<Node *> q;
31+
if (root)
32+
q.push(root);
33+
34+
while (!q.empty())
35+
{
36+
// 1. Q theke ber kore ano
37+
Node *f = q.front();
38+
q.pop();
39+
40+
// 2. Jabotiyo ja kaj ache koro
41+
int l, r;
42+
cin >> l >> r;
43+
44+
Node *left, *right;
45+
46+
if (l == -1)
47+
left = NULL;
48+
else
49+
left = new Node(l);
50+
51+
if (r == -1)
52+
right = NULL;
53+
else
54+
right = new Node(r);
55+
56+
f->left = left;
57+
f->right = right;
58+
59+
// 3. Children gulo k push koro
60+
if (f->left)
61+
q.push(f->left);
62+
if (f->right)
63+
q.push(f->right);
64+
}
65+
return root;
66+
}
67+
68+
int count_height(Node *root)
69+
{
70+
if (!root)
71+
return 0;
72+
int l = count_height(root->left);
73+
int r = count_height(root->right);
74+
return max(l, r) + 1;
75+
}
76+
77+
int main()
78+
{
79+
Node *root = input_binary_tree();
80+
cout << count_height(root) << endl;
81+
82+
return 0;
83+
}

count_max_height_of_a_binary_tree.exe

83 KB
Binary file not shown.

input.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
10 20 50 30 40 70 60 -1 -1 -1 -1 -1 80 -1 -1 -1 -1
1+
10 20 30 70 150 120 40 80 90 -1 -1 130 -1 60 50 -1 -1 100 -1 -1 140 -1 -1 -1 -1 -1 110 -1 -1 -1 -1

output.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
4
1+
6

0 commit comments

Comments
 (0)