节点是否为空,即使它有一个值?
Node is null even though it has a value?
>我正在尝试基于整数数组制作一个二叉搜索树。
我创建了一个函数 BST,它将数组及其大小作为参数。现在,我在数组的每个项目上调用另一个函数makeBST,该函数采用根节点和该值。它会创建另一个节点,并根据值将其与根节点附加。
但是 makeBST 函数不会递归自身并为数组的每个值执行 NULL 条件,即使根节点不为 null 也是如此
#include<iostream>
#include<cmath>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
};
Node *newNode(int x){
Node *node = new Node();
node->data = x;
node->left=NULL;
node->right = NULL;
return node;
};
void makeBST(Node *node, int x){
if(node==NULL){
// keep getting executed even though root node has a value.
// here must be error.
cout << " NULL condition " << endl;
node = newNode(x);
return;
};
if((node->data) > x){
cout << "also working" << endl;
makeBST(node->left,x);
}else if((node->data) < x){
makeBST(node->right,x);
};
};
Node *BST(int arr[], int n){
Node *root = newNode(arr[0]);
for(int i=1; i<=n-1; i++){
cout << "loop" << i << endl;
makeBST(root,arr[i]);
};
return root;
};
int main(){
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int n=10;
Node *root = BST(arr,n);
return 0;
};
我知道这不是创建二叉搜索树的最佳方式。但我是一个初学者,这是我能想到的。
谁能帮忙?
目前,您正在更改函数中 (*node( 的局部值,而不会对传递给它的变量node
产生任何影响。您应该阅读有关将指针作为值传递与作为引用传递的信息。
如果要更改node
则需要将其作为引用传递:
void makeBST(Node **node, int x) {
if(*node==NULL){
cout << " NULL condition " << endl;
node = &newNode(x);
return;
};
if((*node->data) > x){
cout << "also working" << endl;
makeBST(&(*node->left),x);
}else if((*node->data) < x){
makeBST(&(*node->right),x);
};
};
确保在调用makeBST
时传递节点的地址。
相关文章:
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 节点是否为空,即使它有一个值?
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 除了 std::vector 之外,是否有一个 std 容器不会复制和销毁作为类的元素?
- 是否有一个库可以检查C++中的变量类型?
- 是否有一个版本的glCopyImageSubData在Openg GL中使用混合?
- 是否已经有一个 constexpr std::bit_cast 与 g++ 一起使用
- 对于C字符串,是否有一个标准的C++迭代器
- 是否可以有一个模板函数,可以将向量和非向量类型都作为参数
- 是否有一个类似STL的函数来用索引的某个函数填充数组
- 是否有一个C++函数可以准确返回平方根反比的内置 CPU 操作 RSQRTSS 的值?
- 是否有一个标准函数可以打印/监视stdin文件的内容,同时将数据留在stdin中
- C++是否有一个容器,每个类型最多存储一个对象
- C++中是否有一个函数可以为您获取指向该节点的所有指针的地址空间
- 对于std::bitset,是否有一个ffs()等价物
- 是否有一个Windows驱动程序函数可以执行Windows文件api SeFileAttributes的等效功能
- 是否有可能有一个派生类继承最终函数但创建相同的函数(而不是重写)
- C 中是否有一个无法更改的时间戳?(Internet独立)
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 是否有一个函数可以显示我创建的类中的对象到 QTextBrowser 中?