I'm trying to make a binary search tree based on an array of integers.
I've created a function BST that takes an array and its size as a parameter. Now I'm calling another function makeBST on every item of the array that takes the root node and that value. It creates another node and attach it with the root node based on the value.
But the makeBST function is not recursing over itself and executing the NULL condition for every value of the array, even though root node is not 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;
};
I know this is not the best way of creating Binary search tree. But I'm a beginner and this is what i could come up with.
Can anyone help?
Aucun commentaire:
Enregistrer un commentaire