- 思路
深度优先搜索
private:
int res = 0;
int dfs(TreeNode* cur)
{
if(cur == nullptr)
{
return 0;
}
if(cur->left != nullptr)
{
int leftSide = dfs(cur->left);
}
if(cur->right != nullptr)
{
int rightSide = dfs(cur->right);
}
res = max(res, leftNode + rightNode);//维护最大的二叉树直径
return max(leftNode, rightNode) + 1;//返回该节点的最大深度
}
public:
int diameterOfBinaryTree(TreeNode* root)
{
int res = INT_MIN;
dfs(root);
return res;
}