-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiameter_of_Binary_Tree.cpp
More file actions
53 lines (42 loc) · 1.26 KB
/
Copy pathdiameter_of_Binary_Tree.cpp
File metadata and controls
53 lines (42 loc) · 1.26 KB
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
#include <stdio.h>
#include <malloc.h>
#include <limits.h>
/* nodes for queue and tree node*/
struct node {
int key;
struct node * left;
struct node * right;
};
/* function for creating new node of tree*/
struct node *newNode(int data)
{
struct node *node = (struct node *)malloc(sizeof(struct node));
node->key = data;
node->left = NULL;
node->right = NULL;
return (node);
}
/* function to determine the diameter of a binary tree */
int diameterofBinaryTree(struct node * root,int & diameter){
if(root == NULL)return 0;
int left = diameterofBinaryTree(root->left,diameter);
int right = diameterofBinaryTree(root->right,diameter);
int max_diameter = left + right +1;
if (diameter < max_diameter) diameter = max_diameter;
if (left > right) return left + 1;
else return right +1;
}
int main(){
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->left = newNode(7);
root->right->left->right = newNode(8);
int diameter = 0;
diameterofBinaryTree(root,diameter);
printf("%d is the diameter of the tree",diameter);
return 0;
}