考察知识点: 树的遍历、递归、深度优先搜索
题目分析:
题目要求找到牛群中的最高牛,即树中的最大结点。只需要遍历一遍树即可。
树的遍历一般使用递归
的方法:
- 若是一颗
空树
,直接返回最高牛是0; - 若是只有
一个结点
的树,那么最高牛就是该结点。 - 否则最高牛是树根
左子树
和右子树
中的最高牛。
所用编程语言: 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) {
// write code hero
if (!root) return 0;
if (!root->left && !root->right) return root->val;
return max(findMaxHeight(root->left), findMaxHeight(root->right));
}
};