-
Notifications
You must be signed in to change notification settings - Fork 488
/
Height_of_Tree.cpp
77 lines (59 loc) Β· 1.29 KB
/
Height_of_Tree.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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int value;
struct Node *left, *right;
struct Node *root;
};
struct Node *create ( int val )
{
struct Node *p = new Node;
p->value = val;
p->left = p->right = NULL;
p->root = NULL;
return p;
}
struct Node* tree(Node* t, int v){
if (t == NULL)
return create(v);
if (v < t->value)
t->left = tree(t->left, v);
else
t->right = tree(t->right, v);
return t;
}
///------------Height of the binary tree------------///
int height( struct Node* p )
{
if ( p == NULL )
return 0;
if ( p->left == NULL && p->right == NULL )
return 1;
else{
int l = height( p->left );
int r = height( p->right );
return 1 + (l > r ? l : r );
}
}
// Driver functions
int main()
{
int size;
Node *root = new Node;
root = NULL;
cout<<"Enter the size of array : ";
cin>>size;
int a[size];
cout<<"Enter the elements in array : ";
for(int i=0;i<size;i++)
{
cin>>a[i];
}
for(int i = 0; i < size; i++)
{
root = tree(root, a[i]);
}
cout << "\n Height of tree: "<<height( root ) << endl;
return 0;
}