【发布时间】:2020-04-27 05:08:54
【问题描述】:
我正在尝试实现一个 python 代码来查找二叉树的深度。我已经成功实现了 C++ 版本,但是当我在 python 中实现相同的代码时,它在 Leetcode 中给出了不同的答案。 C++ 版本:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
int l=maxDepth(root->left);
int r=maxDepth(root->right);
return 1 + max(l, r);
}
Python 版本:
class Solution(object):
def maxDepth(self, root):
if root is None:
return 0
self.left=self.maxDepth(root.left)
self.right=self.maxDepth(root.right)
return max(self.left,self.right) +1
在 Python 和 C++ 中进行递归调用的方式有什么根本区别吗?我的python代码因以下情况而失败:[1,2,3,4,5]
【问题讨论】:
标签: recursion binary-tree