计算二叉搜索树C++中的节点数
Counting number of nodes in Binary Search Tree C++
我正在努力理解为什么下面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
时,left
和right
变量被NULL
,因此整个CountNodes
函数只返回等于n
int 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);
}
相关文章:
- 反向给定链表中的K节点
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Boost Graph Library,修复节点大小
- C++A*算法并不总是在路径中具有目标节点
- 如何找到2个单链表的公共节点
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 为什么我的删除节点函数实际上没有删除节点?
- 我们可以删除链表中静态内存中的节点吗
- 如何在pugixml中获取节点的内部XML
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 节点 *temp; 和节点 *tmp = 新节点之间的差异
- 引擎节点:未定义的符号:_ZTV6Config
- 为什么"delete"关键字不删除节点?
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 如何按数字顺序插入链表节点?
- 为什么我的双向链表删除函数会删除多个节点?
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限