题解 | #牛群的最大高度# 二叉树的遍历
牛群的最大高度
https://www.nowcoder.com/practice/f745023c5ac641c9914a59377dacdacf
知识点
二叉树的遍历 / 树形DP/ 深度优先遍历DFS
题意分析
求给定根节点的二叉树的节点的最大值, 只需要遍历整个二叉树求得最大值即可
遍历二叉树可以使用前序 / 中序 / 后序遍历
下面以前序为例 展示代码
时间复杂度
因为只遍历一次树的节点, 时间复杂度
AC Code (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 here
if (!root) return 0; // 空树
int res = root->val;
if (root->left) res = max(res, findMaxHeight(root->left));
if (root->right) res = max(res, findMaxHeight(root->right));
return res;
}
};
查看7道真题和解析
360集团公司氛围 345人发布