forked from Arnon120/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
543. Diameter of Binary Tree.cpp
64 lines (54 loc) · 1.74 KB
/
543. Diameter of Binary Tree.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <tuple>
#include<algorithm>
#include <iostream>
/*
Note: I do not understand how some of the solutions pass the testing.
*/
// 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 Solution {
public:
struct TreeNode_details{int depth; int diameter;};
TreeNode_details get_TreeNode_details(TreeNode *node) {
int depth{0};
int diameter{0};
int left_depth{0};
int left_diameter{0};
if (node->left != nullptr){
TreeNode_details left_details{get_TreeNode_details(node->left)};
left_depth = left_details.depth;
left_diameter = left_details.diameter;
}
else
{
left_depth = -1;
left_diameter = -1;
}
int right_depth{0};
int right_diameter{0};
if (node->right != nullptr){
TreeNode_details right_details{get_TreeNode_details(node->right)};
right_depth = right_details.depth;
right_diameter = right_details.diameter;
}
else
{
right_depth = -1;
right_diameter = -1;
}
depth = std::max({0,right_depth+1,left_depth+1});
diameter = std::max({0,right_diameter,left_diameter,right_depth+left_depth+2});
return TreeNode_details{depth,diameter};
}
int diameterOfBinaryTree(TreeNode* root) {
TreeNode_details rootDetails{get_TreeNode_details(root)};
return rootDetails.diameter;
}
};