[英]Error when finding the total depth of a binary tree
我想測試一棵二叉樹的總深度,所以我寫了以下代碼:
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(node, depth) ^ SyntaxError: invalid syntax exit status 1
首先,閱讀錯誤:P。 您在第 4 行有一個語法錯誤,並且在您的 def 末尾缺少一個:
。
至於你的算法,不太確定為什么你有nodeDepths
function,它並沒有真正的幫助。
對於您的depthSum
function,您的算法將永遠不會完成,因為您陷入無限遞歸循環 - 由於在 depthSum function 中使用root
而不是node
,您永遠不會真正遍歷樹。
看看這個,這是一個檢查深度的簡單方法:
def traverse(root, depth=0):
if root:
return max(traverse(root.left, depth+1), traverse(root.right, depth+1))
直接調用它
traverse(root)
我沒有看到 nodeDepths function 的用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.