Skip to content

Commit

Permalink
diameter of Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
NripeshKumar committed Oct 11, 2019
1 parent 4300a4c commit 87f26a3
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions Algorithms/Tree/diameterTree/c/diameterTree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* left, *right;
};

struct node* newNode(int data);
int max(int a, int b);
int height(struct node* node);

int diameter(struct node * 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 height(struct node* node)
{

if(node == NULL)
return 0;

return 1 + max(height(node->left), height(node->right));
}

struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

int max(int a, int b)
{
return (a >= b)? a: b;
}

int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

printf("Diameter of the given binary tree is %d\n", diameter(root));

getchar();
return 0;
}

0 comments on commit 87f26a3

Please sign in to comment.