Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
左子树深度 + 右子树深度 + 1 - 1
(题目定义的直径比路径长度少 1),遍历所有节点的直径,最大的即为结果class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int res = 0;
depth(root, res);
return res;
}
int depth(TreeNode* root, int& res) {
if (!root) {
return 0;
}
int l = depth(root->left, res);
int r = depth(root->right, res);
res = max(res, l + r);
return 1 + max(l, r);
}
};