所以我试图学习如何编写我的第一个BST代码,这很难....我已经遇到了几行代码的问题。问题在于插入,但我已经包含了所有内容,以便我可以获得有关我的样式/其他错误的一些反馈。我被建议使用一个指向指针实现的指针,但我们还没有学到它,所以我感觉不舒服/知道如何编码它。
错误是
cc1plus: warnings being treated as errors
tree.cpp: In member function âbool Tree::insert(Tree::Node*&, int, std::string)â:
tree.cpp:34: warning: control reaches end of non-void function
tree.h文件
#ifndef TREE_H
#define TREE_H
#include <iostream>
#include <string>
using namespace std;
class Tree
{
public:
Tree();
bool insert(int k, string s);
private:
struct Node
{
int key;
string data;
Node* left;
Node* right;
};
Node* root;
bool insert(Node*& root, int k, string s);
};
#endif
tree.cpp
#include <iostream>
#include "tree.h"
#include <stack>
#include <queue>
#include <string>
using namespace std;
Tree::Tree()
{
root = NULL;
}
bool Tree::insert(int k, string s)
{
return insert(root, k, s);
}
bool Tree::insert(Node*& currentRoot, int k, string s)
{
if(currentRoot == NULL){
currentRoot = new Node;
currentRoot->key = k;
currentRoot->data = s;
currentRoot->left = NULL;
currentRoot->right = NULL;
return true;
}
else if (currentRoot->key == k)
return false;
else if (currentRoot->key > k)
insert(currentRoot->left, k, s);
else
insert (currentRoot->right,k, s);
}
movieList.cpp
#include <iostream>
#include <stack>
#include <queue>
#include <string>
#include "tree.h"
using namespace std;
int main()
{
Tree test;
test.insert(100, "blah");
return 0;
}
答案 0 :(得分:4)
cc1plus: warnings being treated as errors
tree.cpp: In member function âbool Tree::insert(Tree::Node*&, int, std::string)â:
tree.cpp:34: warning: control reaches end of non-void function
这只是说你没有在每条可能的道路上回归。试试这个:
bool Tree::insert(Node*& currentRoot, int k, string s)
{
if(currentRoot == NULL){
currentRoot = new Node;
currentRoot->key = k;
currentRoot->data = s;
currentRoot->left = NULL;
currentRoot->right = NULL;
return true;
}
else if (currentRoot->key == k)
return false;
else if (currentRoot->key > k)
return insert(currentRoot->left, k, s);
// ^^^^^^
else
return insert (currentRoot->right,k, s);
// ^^^^^^
}
答案 1 :(得分:1)
怎么样:
bool Tree::insert(Node*& currentRoot, int k, string s)
{
if(currentRoot == NULL){
currentRoot = new Node;
currentRoot->key = k;
currentRoot->data = s;
currentRoot->left = NULL;
currentRoot->right = NULL;
return true;
}
else if (currentRoot->key == k)
return false;
else if (currentRoot->key > k)
insert(currentRoot->left, k, s);
else
insert (currentRoot->right,k, s);
return true;
}
所有分支都需要返回一个值(在这种情况下为布尔值)。