Skip to content

Commit 5abceee

Browse files
committed
Height of tree
1 parent 446d63e commit 5abceee

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

Tree/heightOfTree.cpp

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
// Node class
6+
class Node
7+
{
8+
public:
9+
int data;
10+
Node *left;
11+
Node *right;
12+
13+
Node(int val)
14+
{
15+
data = val;
16+
left = right = NULL;
17+
}
18+
};
19+
20+
static int idx = -1;
21+
Node *buildTree(vector<int> preorder)
22+
{
23+
idx++;
24+
25+
// base case
26+
if (preorder[idx] == -1)
27+
{
28+
return NULL;
29+
}
30+
31+
// create root node
32+
Node *root = new Node(preorder[idx]);
33+
34+
// left sub tree recursion call
35+
root->left = buildTree(preorder);
36+
37+
// left sub tree recursion call
38+
root->right = buildTree(preorder);
39+
40+
return root;
41+
}
42+
43+
// height of tree
44+
int height(Node *root)
45+
{
46+
// base case
47+
if (root == NULL)
48+
{
49+
return 0;
50+
}
51+
52+
// left subtree call
53+
int leftHt = height(root->left);
54+
55+
// right subtree call
56+
int rightHt = height(root->right);
57+
58+
return max(leftHt, rightHt) + 1;
59+
}
60+
61+
int main()
62+
{
63+
vector<int> preorder = {1, 2, -1, -1, 3, 4, -1, -1, 5, -1, -1};
64+
Node *root = buildTree(preorder);
65+
66+
cout << "height : " << height(root) << endl;
67+
68+
return 0;
69+
}

Tree/heightOfTree.exe

67.2 KB
Binary file not shown.

0 commit comments

Comments
 (0)