我只是想在面试之前复习一些数据结构。但是,每当我尝试在Visual Studio 2017中运行此代码时,都不会收到错误或输出。奇怪的是,运行该程序后,先给出输出的程序不再提供给者输出。任何帮助表示赞赏。该程序由三个文件组成。
TreeHead.h:
class BST
{
private:
struct node
{
int key;
node *left;
node *right;
};
node *root;
void addLeafPrivate(int key, node *Ptr);
void printOrderedPrivate(node *Ptr);
public:
BST();
node* createLeaf(int key);
void addLeaf(int key);
void printOrdered();
};
def.cpp:
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "TreeHead.h"
using namespace std;
BST::BST()
{
root = NULL;
}
BST::node* BST::createLeaf(int key)
{
node *n = new node;
n->key = key;
n->left = NULL;
n->right = NULL;
return n;
}
void BST::addLeaf(int key)
{
addLeafPrivate(key, root);
}
void BST::addLeafPrivate(int key, node* Ptr)
{
if (root == NULL)
{
root = createLeaf(key);
}
else if (key < Ptr->key)
{
if (Ptr->left != NULL)
{
addLeafPrivate(key, Ptr->left);
}
else
{
Ptr->left = createLeaf(key);
}
}
else if (key > Ptr->key)
{
if (Ptr->right != NULL)
{
addLeafPrivate(key, Ptr->right);
}
else
{
Ptr->right = createLeaf(key);
}
}
else
{
cout << "The key has already been added to the tree."
}
}
void BST::printOrdered();
{
void printOrderedPrivate(root);
}
void BST::printOrderedPrivate(node *Ptr);
{
cout << Ptr << endl;
if (root != NULL)
{
if (Ptr->left != NULL)
{
printOrderedPrivate(Ptr->left);
}
if (Ptr->right != NULL)
{
printOrderedPrivate(Ptr->right);
}
}
else
{
cout << "Aint no Tree" << endl;
}
}
Trees.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "TreeHead.h"
#include "def.cpp"
using namespace std;
int main()
{
int treeNodes[27] = { 5, 32, 21, 25, 6, 8, 45, 12, 6, 5, 64, 654, 5, 16, 54, 178, 494, 1, 13, 21, 321, 47, 4, 46, 6, 1212, 6};
BST zekeTree;
zekeTree.printOrdered();
for (int i = 0; i < treeNodes.size; i++)
{
zekeTree.addLeaf(zekeTree[i]);
}
zekeTree.printOrdered();
cout << "hello world" << endl;
system("pause");
return 0;
}
答案 0 :(得分:0)
您的代码中存在多个错误。
您正在运行的程序不是您在此处显示的程序,它将无法编译。
在您犯的错误中:
请不要在此处为函数的返回类型添加前缀
BST::node* BST::createLeaf(int key) // wrong
node* BST::createLeaf(int key) // correct
您应该采取保护措施,以避免在标头中使用多个类定义。
#pragma once // add this
在下面的位中,在参数()后面有半列,该半列不应位于此处,并且不应指定正在调用的函数的类型:
void BST::printOrdered(); // <---- ; should be removed
{
void printOrderedPrivate(root); // void should not be specified here
}
void BST::printOrdered() // fixd
{
printOrderedPrivate(root);
}
数组数据结构不提供大小参数或方法,您将其与std :: vector混淆了。
如果您没有定义适当的运算符,则以下行将无法编译,因为[]操作在类BST中没有意义:
zekeTree.addLeaf(zekeTree[i]);