我在二叉搜索树上做作业。我们获得了一个头文件,我们不允许改变它。
我有一个创建BST的功能,其中包含要存储的初始值,一个通过复制现有树来创建BST的函数以及一个插入BST的函数。
我正在努力找出什么是错的,我在网上寻求帮助的地方总是有不同的头文件我不能做。任何帮助将不胜感激。
#include "stdafx.h"
#include "bst.h"
// Creating nodes
Node* tree;
Node* treeNew;
// Creates an empty binary tree - 1
BinarySearchTree::BinarySearchTree()
{
treeNew = nullptr;
}
// Creates a binary tree with an initial value to store - 2
BinarySearchTree::BinarySearchTree(std::string word)
{
Node *tree = new Node;
tree->left = nullptr;
tree->right = nullptr;
tree->data = word;
}
// Creates a binary tree by copying an existing tree - 3
BinarySearchTree::BinarySearchTree(const BinarySearchTree &rhs)
{
if (tree != NULL) {
Node *treeNew = new Node;
treeNew->data = tree->data;
Node *leftTreeNew = new Node;
leftTreeNew = tree->left;
Node *rightTreeNew = new Node;
rightTreeNew = tree->right;
}
else {
treeNew = NULL;
}
}
// Adds a word to the tree
void BinarySearchTree::insert(std::string word)
{
Node *nextNode = tree;
Node *currentNode;
while (nextNode != NULL) {
currentNode = nextNode;
if (word < currentNode->data) {
nextNode = currentNode->left;
} else {
nextNode = currentNode->right;
}
}
}
这是我的头文件
#pragma once
#include <iostream>
#include <string>
// Node of the tree
struct Node
{
// Data stored in this node of the tree
std::string data;
// The left branch of the tree
Node *left = nullptr;
// The right branch of the tree
Node *right = nullptr;
};
class BinarySearchTree
{
private:
// Pointer to root of the tree
Node *root = nullptr;
public:
// Creates an empty binary tree
BinarySearchTree();
// Creates a binary tree with an inital word to store
BinarySearchTree(std::string word);
// Creates a binary tree by copying an existing tree
BinarySearchTree(const BinarySearchTree &rhs);
// Destroys (cleans up) the tree
~BinarySearchTree();
// Adds a word to the tree
void insert(std::string word);
// Removes a word from the tree
void remove(std::string word);
// Checks if a word is in the tree
bool exists(std::string word) const;
// Creates a string representing the tree in alphabetical order
std::string inorder() const;
// Creates a string representing the tree in pre-order
std::string preorder() const;
// Creates a string representing the tree in post-order
std::string postorder() const;
// Checks if two trees are equal
bool operator==(const BinarySearchTree &other) const;
// Checks if two trees are not equal
bool operator!=(const BinarySearchTree &other) const;
// Reads in words from an input stream into the tree
friend std::istream& operator>>(std::istream &in, BinarySearchTree &tree);
// Writes the words, in-order, to an output stream
friend std::ostream& operator<<(std::ostream &out, const BinarySearchTree &tree);
};
答案 0 :(得分:0)
您的代码存在许多错误,您需要更正它们。
例如,
在函数insert(std :: string word)中,如果树为null,则无需执行任何操作,但实际上您应该创建一个节点(值为&#34; word&# 34;)并插入它。同样,根可能会有时改变,你必须考虑它。
在函数BinarySearchTree(const BinarySearchTree&amp; rhs)中,你永远不会使用rhs。此外,我猜你的意思是深层次的,所以你的代码根本无法工作。
我的建议是你应该重写你的功能(在充分了解BST之后)。同时,您可以尽快清楚地描述您的问题。