/**
* 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;
}
};