Skip to content

Commit 7811510

Browse files
committed
Diameter of Binary Tree
1 parent 5fca426 commit 7811510

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// we will be writing the code for the problem finding the diameter of a binary Tree
2+
#include<iostream>
3+
#include<algorithm>
4+
using namespace std;
5+
struct Node{
6+
int data;
7+
Node* left;
8+
Node* right;
9+
Node(int val) : data(val), left(nullptr), right(nullptr) {}
10+
};
11+
int ans;
12+
int depth(Node * root){
13+
if(root == NULL){
14+
return 0;
15+
}
16+
int left = depth(root->left);
17+
int right = depth(root->right);
18+
ans = max(ans, left + right);
19+
return max(left, right) + 1;
20+
}
21+
int diameterofbinaryTree(Node * root){
22+
ans = 0;
23+
depth(root);
24+
return ans;
25+
}
26+
int main(){
27+
Node * root = new Node(1);
28+
root->left = new Node(2);
29+
root->right = new Node(3);
30+
root->left->left = new Node(4);
31+
root->left->right = new Node(5);
32+
root->right->left = new Node(6);
33+
root->right->right = new Node(7);
34+
cout << "Diameter of the binary tree is: " << diameterofbinaryTree(root) << endl;
35+
return 0;
36+
}

0 commit comments

Comments
 (0)