[英]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.