随机生成的二叉搜索树C ++

时间:2017-05-06 13:41:14

标签: c++ tree

生成随机二叉搜索树(到.txt文件)有一个小问题。首先,我只尝试了一个随机插入,效果很好,但是当我尝试生成整个树(用于循环)时,它不起作用。

在我的代码中,方法是 Create_tree (基于用户输入)。 for循环称为count_nodes次,但第一个条件(nod == nullptr)只调用一次。

我的代码:

tree.h中

#include <fstream> 
using namespace std;

class BinaryTree
{
public:
    BinaryTree();
    ~BinaryTree();
    void Create_tree(int count_nodes);
    void treeToFile(ofstream& file);

private:
    struct node
    {   
        int key;
        node* left;
        node* right;
    };
    node* root;
    void Clear(node* nod);
    void Create_tree(int count_nodes, node*& nod);
    void treeToFile(node* nod, ofstream& file);
};

Tree.cpp

#include "Tree.h"
#include<iostream>
#include<fstream>
#include <stdlib.h>     
#include <time.h>

using namespace std;

BinaryTree::BinaryTree()
{
    root = nullptr;
}

BinaryTree:: ~BinaryTree()
{
    cout << "Clear Binary Tree" << endl;
    Clear(root);
}

void BinaryTree::Clear(node* nod)
{
    if (nod != nullptr)
    {
        Clear(nod->left); 
        Clear(nod->right);
        cout <<"Deleting node: " <<nod->key << endl;
        delete nod;
    }
}

void BinaryTree::Create_tree(int count_nodes)
{
    Create_tree(count_nodes, root);
}

void BinaryTree::Create_tree(int count_nodes, node*& nod)
{

    for(int i = 0; i < count_nodes;i++)
    {
        srand(time(NULL));
        int x = rand() % 100 + 1;
        if (nod == nullptr) 
        {
            nod = new node();
            nod->left = nullptr;
            nod->right = nullptr;
            nod->key = x;
        }
        if (x<nod->key) 
            Create_tree(x, nod->left);
        else
            if (x>nod->key) 
                Create_tree(x, nod->right);
    }
}

void BinaryTree::treeToFile(ofstream & file)
{   
    treeToFile(root, file);

}

void BinaryTree::treeToFile(node* root, ofstream& file)
{
    if (!file.is_open()){
        cout << "File cannot be opened" << endl;
    }
    if (root == NULL) {
        file << "#" << " ";
        return;
    }
    else{
    file << root->key << " ";
    treeToFile(root->left, file);
    treeToFile(root->right, file);
    }

}

void BinaryTree::fileToTree()
{
    ifstream file("tree.txt");
    fileToTree(root,file);
    file.close();
}

Main.cpp的

#include "Tree.h"
#include<iostream>
#include<string>
#include <stdlib.h>     
#include <time.h>

using namespace std;

int main()
{
    int count_nodes = 0;
    BinaryTree* tree = new BinaryTree();
    cout << "Number of generated nodes:" << endl;
    cin >> count_nodes;
    tree->Create_tree(count_nodes);
    ofstream output("tree.txt");
    tree->treeToFile(output);
    output.close();

    delete tree;
    return 0;
}

0 个答案:

没有答案