节点是否为空,即使它有一个值?

Node is null even though it has a value?

本文关键字:有一个 是否 节点      更新时间:2023-10-16

>我正在尝试基于整数数组制作一个二叉搜索树。

我创建了一个函数 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时传递节点的地址。

相关文章: