andrewb
andrewb

Reputation: 5339

How can I get number of leaf nodes in binary tree non-recursively?

I have a practice question that I'm stumped on - to get the number of leaf nodes in a binary tree without using recursion. I've had a bit of a look around for ideas, I've seen some such as passing the nodes to a stack, but I don't see how to do it when there's multiple branches. Can anyone provide a pointer?

Upvotes: 0

Views: 5056

Answers (1)

Techie
Techie

Reputation: 11

NumberOfLeafNodes(root);
int NumberOfLeafNodes(NODE *p)
{
    NODE *nodestack[50];
    int top=-1;
    int count=0;
    if(p==NULL)
        return 0;
    nodestack[++top]=p;
    while(top!=-1)
    {
        p=nodestack[top--];
        while(p!=NULL)
        {
            if(p->leftchild==NULL && p->rightchild==NULL)
                count++;
            if(p->rightchild!=NULL)
                nodestack[++top]=p->rightchild;
            p=p->leftchild;      
        }
    }
return count;
}

Upvotes: 1

Related Questions