postorder O(n) time O(h) space
需要考虑的几个case
- nullptr
- single node
- 其他
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
|
class Solution { public: int diameter(Node* root) { dfs(root); return res; }
int dfs(Node *root) { if (!root) return 0; int mx = 0, submx = 0; for (auto child : root->children) { int len = dfs(child) + 1; if (len > mx) { submx = mx; mx = len; } else if (len > submx) { submx = len; } } res = max(res, mx + submx); return mx; }
int res = 0; };
|