简体   繁体   中英

Counting nodes of a binary tree without recursion Python

I know how to do it recursively:

def num_nodes(tree):
if not tree.left and not tree.right:
    return 1
else:
    return 1 + num_nodes(tree.left) + num_nodes(tree.right)

But how would you do it non recursively? Having trouble accessing a node that's on the right of a left subtree.

You could store the nodes you have to do in a list.

queue = []
count = 0
queue.append(root)
# Above is start of tree

while(queue):
  if queue[0].left:
    queue.append(queue[0].left)
  if queue[0].right:
    queue.append(queue[0].right)
  queue.pop(0)
  count += 1

Which should work as long as your tree does not have any loops in it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM