题解 | #牛群排列的最大深度# 递归
牛群排列的最大深度
https://www.nowcoder.com/practice/b3c6383859a142e9a10ab740d8baed88
知识点
二叉树 递归
思路
二叉树的最大深度,等于左右子树的最大深度中的较大值+1;因此可以先求子树的最大深度,而这是一个和原问题一样的子问题,可以用递归解决。递归终点是空节点,深度为0。
时间复杂度
只遍历一遍二叉树
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 maxDepth(TreeNode* root) {
if (!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
叮咚买菜公司氛围 118人发布