forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0543-diameter-of-binary-tree.cpp
40 lines (35 loc) · 1004 Bytes
/
0543-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
/*
Given root of binary tree, return length of diameter of tree (longest path b/w any 2 nodes)
Max path b/w 2 leaf nodes, "1 +" to add path
Time: O(n)
Space: O(n)
*/
/**
* 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) {}
* };
*/
classSolution {
public:
intdiameterOfBinaryTree(TreeNode* root) {
int result = 0;
dfs(root, result);
return result;
}
private:
intdfs(TreeNode* root, int& result) {
if (root == NULL) {
return0;
}
int left = dfs(root->left, result);
int right = dfs(root->right, result);
result = max(result, left + right);
return1 + max(left, right);
}
};