-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathBinaryTreeDiameter.cpp
31 lines (29 loc) · 1.08 KB
/
BinaryTreeDiameter.cpp
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
//Problem: https://leetcode.com/problems/diameter-of-binary-tree/
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class BinaryTreeDiameter {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (root == nullptr) return 0;
int diameter = 0;
diameter = max(diameter, (1 + getHeight(root->left) + 1 + getHeight(root->right)));
diameter = max(diameter, diameterOfBinaryTree(root->left));
diameter = max(diameter, diameterOfBinaryTree(root->right));
return diameter;
}
private:
int getHeight(TreeNode* root) {
if (root == nullptr) return -1;
int height = 0;
if (root->left != nullptr) height = max(height, 1 + getHeight(root->left));
if (root->right != nullptr) height = max(height, 1 + getHeight(root->right));
return height;
}
};