在 Python 中查找二叉树的深度

Finding depth of binary tree in Python

我正在尝试实现一个 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]

您的代码不相同。 self.left 表示在 Python 的情况下,您正在修改 Solution 对象的字段(参见 .Explaining the python 'self' variable to a beginner)。要使用局部变量,请放弃使用 self 前缀。