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

Counting number of nodes in Binary Search Tree C++

本文关键字:节点 C++ 搜索树 计算      更新时间:2023-10-16

我正在努力理解为什么下面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并说,是的,它不为 null,将 1 添加到计数器n,然后调用CountNodes(pointer to 10)然后它只会再次将我们发送到左分支以5。然后,当在5时,leftright变量被NULL,因此整个CountNodes函数只返回等于nint 3

我想我正在努力准确理解CountNodes参数的值何时更新。我们是否查看right并检查它是否NULL并更新计数器,然后再将第一次递归调用中的参数值更新为左侧外观中的CountNodes(pointer to 10),即使右侧外观出现在代码中的左侧递归调用之后?

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