题解 | #牛群的最长距离#
牛群的最长距离
https://www.nowcoder.com/practice/82848c6aa1f74dd1b95d71f3c35c74d5
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <queue>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
// 左右节点的最大深度和
void dfs(TreeNode* root, int high, int &max_high)
{
if(!root)
{
max_high = max(max_high, high);
return;
}
// 左子树的最大深度
dfs(root->left, high+1, max_high);
// 右子树的最大深度
dfs(root->right, high+1, max_high);
}
int diameterOfBinaryTree(TreeNode* root) {
// write code here
// 广度优先搜索 + 深度优先搜索
if(!root)
return 0;
queue<TreeNode*>q;
q.push(root);
int ans = 0;
while(!q.empty())
{
int len = q.size();
for(int i=0; i<len; ++i)
{
TreeNode* t = q.front();
q.pop();
int t_high_l = 0, t_high_r = 0;
dfs(t->left, 0, t_high_l);
dfs(t->right, 0, t_high_r);
ans = max(ans, t_high_l+t_high_r);
if(t->left)
q.push(t->left);
if(t->right)
q.push(t->right);
}
}
return ans;
}
};
虚数五行区解题中心 文章被收录于专栏
非淡泊无以明志,非宁静无以致远

查看13道真题和解析
上海得物信息集团有限公司公司福利 1164人发布