543. 二叉树的直径
作者:互联网
- 思路
深度优先搜索
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;
}
标签:return,cur,int,res,nullptr,dfs,543,二叉树,直径 来源: https://blog.csdn.net/qq_43287931/article/details/121542879