问题描述
我正在尝试编写一个计算二进制搜索树节点数的函数。但是,执行该函数时出现错误。这是错误:'NoneType'对象没有属性'right'。该错误是由于行p = p.right。
让我知道是否要提供更多数据。
功能如下:
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