题解 | #牛群的最大高度#
牛群的最大高度
https://www.nowcoder.com/practice/f745023c5ac641c9914a59377dacdacf
考察的知识点:二叉树的遍历、递归;
解答方法分析:
- 首先判断根节点是否为空,如果为空,则返回 0。
- 初始化最大高度为当前节点的值。
- 如果左子树不为空,递归调用
findMaxHeight函数来获取左子树的最大高度,并将其与当前最大高度比较,更新最大高度。 - 如果右子树不为空,递归调用
findMaxHeight函数来获取右子树的最大高度,并将其与当前最大高度比较,更新最大高度。 - 返回最大高度。
所用编程语言:C++;
完整编程代码:↓
/**
* 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 findMaxHeight(TreeNode* root) {
if (!root)
return 0;
int maxHeight = root->val;
if (root->left)
maxHeight = max(maxHeight, findMaxHeight(root->left));
if (root->right)
maxHeight = max(maxHeight, findMaxHeight(root->right));
return maxHeight;
}
};
