Skip to content

Commit 4ef6209

Browse files
authored
Height of Binary tree.cpp
1 parent 4328319 commit 4ef6209

File tree

1 file changed

+122
-0
lines changed

1 file changed

+122
-0
lines changed

Height of Binary tree.cpp

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
struct Node
5+
{
6+
int data;
7+
struct Node *left;
8+
struct Node *right;
9+
10+
Node(int val) {
11+
data = val;
12+
left = right = NULL;
13+
}
14+
};
15+
16+
// Function to Build Tree
17+
Node* buildTree(string str)
18+
{
19+
// Corner Case
20+
if(str.length() == 0 || str[0] == 'N')
21+
return NULL;
22+
23+
// Creating vector of strings from input
24+
// string after spliting by space
25+
vector<string> ip;
26+
27+
istringstream iss(str);
28+
for(string str; iss >> str; )
29+
ip.push_back(str);
30+
31+
// Create the root of the tree
32+
Node *root = new Node(stoi(ip[0]));
33+
34+
// Push the root to the queue
35+
queue<Node*> queue;
36+
queue.push(root);
37+
38+
// Starting from the second element
39+
int i = 1;
40+
while(!queue.empty() && i < ip.size()) {
41+
42+
// Get and remove the front of the queue
43+
Node* currNode = queue.front();
44+
queue.pop();
45+
46+
// Get the current node's value from the string
47+
string currVal = ip[i];
48+
49+
// If the left child is not null
50+
if(currVal != "N") {
51+
52+
// Create the left child for the current Node
53+
currNode->left = new Node(stoi(currVal));
54+
55+
// Push it to the queue
56+
queue.push(currNode->left);
57+
}
58+
59+
// For the right child
60+
i++;
61+
if(i >= ip.size())
62+
break;
63+
currVal = ip[i];
64+
65+
// If the right child is not null
66+
if(currVal != "N") {
67+
68+
// Create the right child for the current node
69+
currNode->right = new Node(stoi(currVal));
70+
71+
// Push it to the queue
72+
queue.push(currNode->right);
73+
}
74+
i++;
75+
}
76+
77+
return root;
78+
}
79+
80+
// } Driver Code Ends
81+
82+
83+
//User function template for C++
84+
85+
/*
86+
struct Node
87+
{
88+
int data;
89+
struct Node* left;
90+
struct Node* right;
91+
92+
Node(int x){
93+
data = x;
94+
left = right = NULL;
95+
}
96+
};
97+
*/
98+
class Solution{
99+
public:
100+
int height(struct Node* node){
101+
// code here
102+
if(node==NULL)
103+
return 0;
104+
return max(height(node->left),height(node->right))+1;
105+
}
106+
};
107+
108+
// { Driver Code Starts.
109+
int main()
110+
{
111+
int t;
112+
scanf("%d ",&t);
113+
while(t--)
114+
{
115+
string treeString;
116+
getline(cin,treeString);
117+
Node* root = buildTree(treeString);
118+
Solution ob;
119+
cout<<ob.height(root)<<endl;
120+
}
121+
return 0;
122+
} // } Driver Code Ends

0 commit comments

Comments
 (0)