forked from amanss00/ForNewbies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheight_of_tree.cpp
50 lines (44 loc) · 950 Bytes
/
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
// C++ program to find height of tree / Depth of tree
#include <bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node* left;
node* right;
};
int DepthOfTree(node* node)
{
if (node == NULL)
return 0;
else {
int leftDepth = DepthOfTree(node->left);
int rightDepth = DepthOfTree(node->right);
/* use the larger one */
if (leftDepth > rightDepth)
return (leftDepth + 1);
else
return (rightDepth + 1);
}
}
node* newNode(int k)
{
node* Node = new node();
Node->data = k;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
int main()
{
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->right->left=newNode(10);
root->right->right=newNode(20);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->right->left = newNode(6);
cout << "Height of tree is " << DepthOfTree(root);
return 0;
}