Reputation: 31
I am learning c language. It's Preety simple to count the leaf nodes in a binary treee using recursion but how can we do it using a queue ?
Upvotes: 0
Views: 549
Reputation: 1416
Do a breadth first traversal of the tree using a queue and check if a particular node has both the children NULL
.
Pseudocode:
queue = [root]
count = 0
while !queue.empty():
current_node = queue.dequeue()
if (current_node.left == NULL) and (current_node.right == NULL):
count += 1
continue
if (current_node.left != NULL):
queue.enqueue(current_node.left)
if (current_node.right != NULL):
queue.enqueue(current_node.right)
print count
Upvotes: 1