[英]Error while counting nodes of binary search tree
我正在嘗試編寫一個 function 來計算二叉搜索樹的節點數。 但是,當我執行 function 時出現錯誤。 這是錯誤:'NoneType' object 沒有屬性'right'。 錯誤是針對 p=p.right 行的。
讓我知道是否要提供更多數據。
這是 function:
def countelements(self, root):
stack=[]
p=root
count=0
while p!=None:
stack.append(p)
p=p.left
count=count+1
while (len(stack)>0):
p=stack.pop()
p=p.right
while p!=None:
p=p.left
stack.append(p)
count=count+1
return count
我還沒有考慮過你的核心邏輯,但是為什么你的堆棧中有一個None
的問題的根源必須是內部循環(參見下面的內聯評論)。
while p!=None:
p=p.left # But what if p.left is None?
stack.append(p)
count=count+1
當您使用遞歸數據結構(例如二叉樹)時,您通常希望使用遞歸。
def count_elements(root):
if root is not None:
left = count_elements(root.left)
right = count_elements(root.right)
return left + right + 1 # +1 for root itself
else:
return 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.