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 65 66 67 68 69 70 71
| 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) { } };
#include <stack> #include <unordered_map>
using std::stack; using std::unordered_map;
class Solution { public: int diameterOfBinaryTree(TreeNode *root) { stack<TreeNode *> stk; unordered_map<TreeNode *, int> node_depth; TreeNode *last = nullptr, *p = root; int res = 0, left_depth, right_depth;
while (p || !stk.empty()) { if (p) { stk.push(p); p = p->left; } else { p = stk.top(); if (p->right && last != p->right) { p = p->right; } else {
left_depth = (p->left) ? node_depth[p->left] : 0;
right_depth = (p->right) ? node_depth[p->right] : 0;
node_depth[p] = std::max(left_depth, right_depth) + 1;
res = std::max(res, left_depth + right_depth);
stk.pop();
last = p; p = nullptr; } } }
return res; } };
|