0%

543. Diameter of Binary Tree

postorder O(n) 跟124. Binary Tree Maximum Path Sum思路基本一致

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return res;
}

int dfs(TreeNode *root) { // 返回以root为根的最长链有几个结点
if (!root) return 0;
int l = dfs(root->left), r = dfs(root->right);
res = max(res, l + r); // 人家问的是边不是点,不要加1
return max(l, r) + 1;
}

int res = 0;
};