如何以非递归方式获取二叉树中叶节点的数量? [英] How can I get number of leaf nodes in binary tree non-recursively?

查看:98
本文介绍了如何以非递归方式获取二叉树中叶节点的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个实践问题,即在不使用递归的情况下获取二叉树中叶节点的数量.我已经到处寻找了一些想法,我已经看到了一些诸如将节点传递到堆栈中的想法,但是当有多个分支时,我看不到如何去做.谁能提供指针?

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?

推荐答案

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;
}

这篇关于如何以非递归方式获取二叉树中叶节点的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆