题解 | #牛群的最长距离#
牛群的最长距离
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) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
int n = 0;
int inorder(TreeNode* root)
{
if (root == nullptr)
return 0;
int l = inorder(root->left);
int r = inorder(root->right);
n = max(n, l + r);
return max(l, r) + 1;
}
int diameterOfBinaryTree(TreeNode* root) {
// write code here
inorder(root);
return n;
}
};
