搜索二叉树中某个高度的节点

时间:2016-06-27 12:01:29

标签: c++ algorithm binary-search-tree

我编写了一个简单的函数,用于计算搜索二叉树中某个高度的节点数,但似乎不起作用。 下面我发布代码:

    int BinTree::nodiH(node* tree,int h,int& N)
{
    int height = 0;
    if(tree==NULL)
        return 0;

    height=max(nodiH(tree->left,h,N),nodiH(tree->right,h,N));

    if(height==h)
        N+=1;

    return 1+height;
}

int BinTree::nodiH(int h)
{
    int N=0;
    nodiH(root_,h,N);

    return N;
}

哪里' h'是我想要计算节点数的高度。 该功能不会返回我期望的内容,我不明白为什么。 如果有人可以帮助我,谢谢你。

1 个答案:

答案 0 :(得分:0)

树的高度是从根部测量的,而不是从树叶测量的 (并且节点的高度"通常被称为"深度",并且还从根测量。是的,它可能令人困惑。)

您需要考虑三种情况 假设非空树的根位于高度1:

  • "树"是叶子或给定高度为零;这棵树上没有这样的节点。
  • 有趣的高度为1;这里有一个节点(tree)。
  • 否则,结果是两个子树中height - 1处节点的总和。

像这样:

int BinTree::nodiH(const node* tree, int h)
{
    if (tree == nullptr || h <= 0)
    {
        return 0;
    }
    else if (h == 1)
    {
        return 1;
    }
    else
    {
        return nodiH(tree->left, h - 1) + nodiH(tree->right, h - 1);
    }
}