c++ - 计算二叉搜索树 C++ 中的节点数

标签 c++ recursion binary-search-tree

我很难理解为什么函数 CountNodes()下面计算 BST 中的所有节点。

如果我们假设我们有以下 BST:

            20
          /   \
         10    30
        /  \  /  \
       5  15 25  35

如果我调用 CountNodes(pointer to root node 20);那么相关的if就不会了声明:

    if(root->left!=NULL)
    {
        n=n+1;
        n=CountNodes(root->left);
    }

简单看节点10并说,是的,它不为空,将计数器加 1 n , 然后调用 CountNodes(pointer to 10)然后将我们再次发送到左侧分支到 5 .然后当在 5 leftright变量是 NULL因此整个CountNodes函数只返回 n等于 int 3 .

我想我很难准确理解 CountNodes 的参数值已更新。我们看看right并检查它是否 NULL并在我们更新第一次递归调用中的参数值之前更新计数器 CountNodes(pointer to 10)在左 View 中,即使右 View 出现在代码中的左递归调用之后?

#include<iostream>
using namespace std;

int n=1;

struct node
{
    int data;
    node* left;
    node* right;
};

struct node* getNode(int data)
{
    node* newNode=new node();
    newNode->data=data;
    newNode->left=NULL;
    newNode->right=NULL;
    return newNode;
}

struct node* Insert(struct node* root, int data)
{
    if (root == NULL)
        return getNode(data);

    if (data < root->data)
        root->left  = Insert(root->left, data);

    else if (data > root->data)
        root->right = Insert(root->right, data);

    return root;
}


int CountNodes(node*root)
{
    if(root==NULL)
        return 0;

    if(root->left!=NULL)
    {
        n=n+1;
        n=CountNodes(root->left);
    }

    if(root->right!=NULL)
    {
        n=n+1;
        n=CountNodes(root->right);
    }
    return n;
}

int main()
{  
    node* root=NULL;
    root=Insert(root,10);
    Insert(root,5);
    Insert(root,20);
    Insert(root,4);
    Insert(root,8);
    Insert(root,15);
    Insert(root,25);
    cout<<"Total No. of Nodes in the BST = "<<CountNodes(root)<<endl;

    return 0;
}

最佳答案

你正在覆盖 n 的值

    n=CountNodes(root->left);

您应该从子树中添加计数。

    n = n + CountNodes(root->left);

还有另一个错误,如果节点有左树和右树,您将对该节点计数两次,如果节点没有子树,则永远不会计数。

if(root->left!=NULL)
{
    n=n+1;                      // Adding one for this node.
    n=CountNodes(root->left);
}

if(root->right!=NULL)
{
    n=n+1;                      // Adding one for this node again?
    n=CountNodes(root->right);
}

我认为你应该这样做:

if(root->left!=NULL)
{
    n = n + CountNodes(root->left);
}

if(root->right!=NULL)
{
    n = n + CountNodes(root->right);
}
n = n + 1;

接下来是在进入函数时检查是否为 null。因此,您无需在执行递归调用之前测试 null。

n = n + CountNodes(root->left);
n = n + CountNodes(root->right);
n = n + 1;

然后我们可以将其简化为:

int CountNodes(node* root)
{
    if (root == nullptr) {
        return 0;
    }
    return 1 + CountNodes(root->left) + CountNodes(root->right);
}

关于c++ - 计算二叉搜索树 C++ 中的节点数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59075669/

相关文章:

c# - 如何从表示 C# 或 VB 中的目录结构的字符串列表创建集合

common-lisp - 在 REPL 中打印 BST?

swift - 递归函数替换json对象

c - 如何避免在这个递归函数中使用malloc?

c - 二叉搜索树的递归

C++ : Running time of next() and prev() in a multiset iterator?

c++ - 后续:从 std::vector 中删除项目

c++ - 标量代码和并行代码之间的不同行为

c++ - 发送包含其他结构的结构作为 ZeroMQ 消息

c++ - 软件或防病毒产品的试用版如何真正发挥作用?