递归求树的深度
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==0)return 0;
int l=1,r=1;
l+=maxDepth(root->left);
r+=maxDepth(root->right);
return l>r?l:r;
}
};
本文介绍了一种使用递归算法来计算二叉树的最大深度的方法。通过递归地计算左子树和右子树的深度,并返回两者中较大值加一的方式实现。此方法简洁高效,适用于计算机科学和数据结构的学习。
递归求树的深度
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==0)return 0;
int l=1,r=1;
l+=maxDepth(root->left);
r+=maxDepth(root->right);
return l>r?l:r;
}
};
被折叠的 条评论
为什么被折叠?