I'm trying to write a function that counts the number of nodes of a binary search tree. However, I'm getting an error when I execute that function. This is the error: 'NoneType' object has no attribute 'right'. The error is for the line p=p.right.
Let me know if more data is to be provided.
Here is the 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
I haven't thought through your core logic, but the source of the problem of why there is a None
inside your stack must be the inner loop (See inline comment below).
while p!=None:
p=p.left # But what if p.left is None?
stack.append(p)
count=count+1
When you work with recursive data structures, such as binary tree, you often want to use recursion.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.