Skip to content

Commit 35d01e5

Browse files
committed
Added solution - LeetHub
1 parent 0b9c308 commit 35d01e5

File tree

1 file changed

+128
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)