Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Recursion 在Python中查找二叉树的深度_Recursion_Binary Tree - Fatal编程技术网

Recursion 在Python中查找二叉树的深度

Recursion 在Python中查找二叉树的深度,recursion,binary-tree,Recursion,Binary Tree,我正在尝试实现一个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->

我正在尝试实现一个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代码在以下情况下失败:

您的代码不相同
self.left
表示在Python中修改
Solution
对象的字段(参见..)。要使用局部变量,请放弃使用
self
前缀。

非常感谢您的回答。我用C++的大部分时间,刚刚开始使用Python,所以我在细节上有点弱。非常感谢您的帮助:)