-
Notifications
You must be signed in to change notification settings - Fork 0
/
diameter_binary_tree.cpp
51 lines (41 loc) · 1016 Bytes
/
diameter_binary_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
#include<bits/stdc++.h>
using namespace std;
class BinaryTreeNode {
public:
int data;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(int data) {
this->data = data;
left = NULL;
right = NULL;
}
~BinaryTreeNode() {
delete left;
delete right;
}
};
int height(BinaryTreeNode* root) {
if (root == NULL) {
return 0;
}
return 1 + max(height(root->left), height(root->right));
}
int diameter (BinaryTreeNode* tree) {
if (tree == NULL)
return 0;
int lheight = height(tree->left);
int rheight = height(tree->right);
int ldiameter = diameter(tree->left);
int rdiameter = diameter(tree->right);
return max(lheight + rheight + 1, max(ldiameter, rdiameter));
}
int main () {
BinaryTreeNode *root = new BinaryTreeNode(1);
root->left = new BinaryTreeNode(2);
root->right = new BinaryTreeNode(3);
root->left->left = new BinaryTreeNode(4);
root->left->right = new BinaryTreeNode(5);
cout << "Diameter - " << diameter(root);
return 0;
}