在BST中检索并输出给定​​值

时间:2019-05-26 05:25:38

标签: c++ algorithm data-structures binary-search-tree

我正在编写代码以创建一个BST,以文本文件中的值填充BST。文本文件包含一个随机的10000个正整数列表,并输出一定的整数。我在打开文件和检索数字时遇到麻烦。

#include<iostream>

#include<fstream>

#include <stdlib.h> //srand, rand

#include <time.h>//clock_t, clock, CLOCKS_PER_SEC

#include<iomanip>

using namespace std;

struct node {

int data;

struct node* left;

struct node* right;

};

struct node* newNode(int data) {

struct node* node = new(struct node); // "new" is like "malloc"

node->data = data;

node->left = NULL;

node->right = NULL;

return(node);

}

struct node* insert(struct node* node, int data) {

// 1. If the tree is empty, return a new, single node

if (node == NULL) {

return(newNode(data));

}

else {

// 2. Otherwise, recur down the tree

if (data <= node->data) node->left = insert(node->left, data);

else node->right = insert(node->right, data);

return(node); // return the (unchanged) node pointer

}

}

/*

Given a binary tree, return true if a node

with the target data is found in the tree. Recurs

down the tree, chooses the left or right

branch by comparing the target to each node.

*/

static int lookup(struct node* node, int target) {

// 1. Base case == empty tree

// in that case, the target is not found so return false

if (node == NULL) {

return(false);

}

else {

// 2. see if found here

if (target == node->data) return(true);

else {

// 3. otherwise recur down the correct subtree

if (target < node->data) return(lookup(node->left, target));

else return(lookup(node->right, target));

}

}

}

void inOrder(struct node *root){

if(root!=NULL){

inOrder(root->left);

cout << root->data<<" ";

inOrder(root->right);

}

}

int main() {

struct node *root= NULL;

char val[10];

ifstream fin; //File reader

clock_t start, end;

fin.open("10000Ints.txt");

if (!fin) {

cerr << "Not able to open 10000Ints.txt file" << endl;

return 1;

}

while(fin >> val){

fin.getline(val, 256, ',');

root = insert(root, atoi(val));

}

cout<<"InOrder Traversal of BST is : "<<endl;

inOrder(root);

cout<<endl;

start = clock();

int find = lookup(root,4);

end = clock();

cout<<fixed<<setprecision(6)<<"Time Taken for Look Up:"<<((end - start))/1000000.0<<endl;

if(!find)

cout<<"\n4 NOT Found";

else

cout<<"4 is Found";

return 0;

}

无法打开文件

0 个答案:

没有答案