gpt4 book ai didi

c++ - 在第一个 BST 上插入非空函数错误的结尾?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:34 27 4
gpt4 key购买 nike

所以我正在尝试学习如何编写我的第一个 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

树.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);
}

电影列表.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;
}

最佳答案

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);
// ^^^^^^
}

关于c++ - 在第一个 BST 上插入非空函数错误的结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5799348/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com