-
Notifications
You must be signed in to change notification settings - Fork 294
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Created Diameter of Binary Tree in CPP
- Loading branch information
1 parent
06e35dd
commit 14846b1
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |