【问题标题】:Error when finding the total depth of a binary tree查找二叉树的总深度时出错
【发布时间】:2020-06-21 03:35:24
【问题描述】:

我想测试一棵二叉树的总深度,所以写了如下代码:


    def nodeDepths(root):
        return depthSum(root, 0)
        
    def depthSum(node, depth)
        if node.left:
            depth += depthSum(root.left, depth+1)
        if node.right:
            depth += depthSum(root.right, depth+1)
        return depth
        
    # This is the class of the input binary tree.
    class BinaryTree:
        def __init__(self, value):
            self.value = value
            self.left = None
            self.right = None

然后我遇到了以下错误,请告诉我如何解决这个问题。

Traceback(最近一次调用最后一次): 文件“main.py”,第 7 行,在 导入 json_wrapper 文件“/tester/json_wrapper.py”,第 3 行,在 导入程序 文件“/tester/program.py”,第 4 行 def depthSum(节点,深度) ^ SyntaxError:无效的语法 退出状态 1

【问题讨论】:

    标签: python binary


    【解决方案1】:

    首先,阅读错误:P。第 4 行有语法错误,并且在 def 末尾缺少 :

    至于你的算法,不太清楚为什么你有nodeDepths 函数,它并没有真正的帮助。

    对于您的 depthSum 函数,您的算法将永远不会完成,因为您会陷入无限递归循环 - 由于在 depthSum 中使用 root 而不是 node,您永远不会真正遍历树功能。

    看看这个,检查深度的简单方法:

    def traverse(root, depth=0):
        if root:
            return max(traverse(root.left, depth+1), traverse(root.right, depth+1))
    

    直接调用它,用

    traverse(root)
    

    我没有看到 nodeDepths 函数的用例。

    【讨论】:

      猜你喜欢
      • 2012-10-12
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多