1. 题目描述
2. 解题思路
(1) 定义一个lambda表达式函数体dfs
,返回以当前节点为根节点的最大深度;
(2) 分别记录下以每个节点作为根节点的左右子树的直径;
(3) 递归调用找出最大值。
3. 代码实现
/**
* 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) {}
* };
*/
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int res = 0;
function<int(TreeNode*)> dfs = [&](TreeNode* root) -> int {
if (!root)
return 0;
// 左子树的深度
int left = dfs(root->left);
// 右子树的深度
int right = dfs(root->right);
// 记录下以每个节点作为根节点的直径
res = max(res, left + right);
// 返回的是以每个点作为根节点的最大深度
return max(left, right) + 1;
};
dfs(root);
return res;
}
};