【问题标题】:Finding depth of binary tree in Python在 Python 中查找二叉树的深度
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 非常感谢您的回答。我大部分时间都在使用 C++,并且刚刚开始使用 Python,所以我对它的细节有点薄弱。非常感谢您的帮助:)
    猜你喜欢
    • 2012-10-12
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多