0

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?

andrewb
  • 5,200
  • 6
  • 36
  • 54
  • 2
    Do a non-recursive walk across the tree and count the leaves. You can replace recursion by a stack, by a queue or by defining the order. – John Dvorak Nov 20 '12 at 04:57
  • 1
    What do you mean `without using recursion`? Any recursive function can be done iteratively. The problem is still recursive though... – beatgammit Nov 20 '12 at 04:58
  • I'll have a look at how to do a non-recursive walk. By recursion, I suppose I mean having a method that calls itself. – andrewb Nov 20 '12 at 05:02
  • I've come up with a bit of a solution based off a simple binary tree walk - should I post it in my question, or just provide it as an answer? Jan what you said is probably enough of an answer.. quite a simple question really. – andrewb Nov 20 '12 at 05:18
  • See http://stackoverflow.com/a/547636/346048 – Reuben Morais Nov 20 '12 at 05:25
  • @ReubenMorais Yep that looks similar to what I've written up, same sort of process. I've just made it keep a count of each node that is a leaf. – andrewb Nov 20 '12 at 10:47
  • @JanDvorak , I know how to replace recursion with a queue, in this question; but I am wondering how we can replace it with stack or defining an order. Could you please explain it more? (I think ordering in this specific question is not important, since we are counting leaves, and we don't need to know order of nodes, but in other binary tree questions, which may need the order, how we can solve the question with stack or a defined order?) – Hengameh Aug 10 '15 at 02:51

1 Answers1

1
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;
}
andrewb
  • 5,200
  • 6
  • 36
  • 54
Techie
  • 11
  • 2
  • Thanks for the response. I don't know this language, I'm guessing Obj-C or C++, can you please explain this code? I can't test it so I can't really mark this as the answer until it at least makes sense to me. – andrewb Jan 30 '13 at 09:44
  • that is C. It assumes a NODE struct type has been defined via typedef. You can see it as some kind of object with left-child and right-child properties. The rest is pretty self-explanatory if you know any other programming language. – stanm87 Aug 29 '13 at 14:57