Skip to content

Commit

Permalink
Created Diameter of Binary Tree in CPP
Browse files Browse the repository at this point in the history
  • Loading branch information
hemantsuteri authored Oct 26, 2022
1 parent 06e35dd commit 14846b1
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions DiameterofBinaryTree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <iostream>
using namespace std;
struct Node {
int data;
Node* leftChild, *rightChild;
};
struct Node* newNode(int data){
struct Node* newNode = new Node;
newNode->data = data;
newNode->leftChild = newNode->rightChild = NULL;
return (newNode);
}
int height(Node* root, int& ans){
if (root == NULL)
return 0;
int left_height = height(root->left, ans);
int right_height = height(root->right, ans);
ans = max(ans, 1 + left_height + right_height);
return 1 + max(left_height, right_height);
}
int diameter(Node* root){
if (root == NULL)
return 0;
int ans = INT_MIN;
int height_of_tree = height(root, ans);
return ans;
}
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 is %d
", diameter(root));
return 0;
}

0 comments on commit 14846b1

Please sign in to comment.