【发布时间】:2019-07-06 03:21:15
【问题描述】:
我是 C++ 编程新手,但我正在尝试创建二叉搜索树。
该程序似乎编译得很好,但它给了我这个错误:
Unhandled exception at 0x009229B7 in Lab001_CS3.exe: 0xC00000FD: Stack
overflow (parameters: 0x00000001, 0x00AD2FBC).
当我尝试运行它时。错误发生在这行代码:
void insert(int value) {
...
}
我不确定我做错了什么,而且我以前从未遇到过这个错误。
代码如下:
#include <iostream>
using namespace std;
//create a node struct
struct node {
//member variables
int key;
node* left;
node* right;
//default constructor
node() {
key = 0;
left = NULL;
right = NULL;
cout << "a new node is created" << endl;
}
//constructor so can create a node in one line
node(int k) {
key = k;
left = NULL;
right = NULL;
cout << "a new node is created" << endl;
}
};
class Tree {
public:
//root node
node root;
//default constructor
Tree() {
root.key = 0;
root.left = NULL;
root.right = NULL;
}
//constructor to create the root node
Tree(int data) {
//set the data to the key
//set the right and left pointers to null
root.key = data;
root.left = NULL;
root.right = NULL;
}
//print the root node
void printRootNode() {
cout << "Root Node - Key: " << root.key << endl;
}
//insert functions
void insert(int value) {
/* If the newNode's key is less than the root key, traverse left
*/
if (value < root.key) {
/* if the left node is NULL */
if (root.left == NULL) {
root.left = new node(value);
cout << "assigned left" << endl;
}
else {
/* if the left node is important */
insert(value);
cout << "recurse" << endl;
}
}
if (value > root.key) {
/* if the right node is NULL */
if (root.right == NULL) {
root.right = new node(value);
cout << "assigned right" << endl;
}
else {
/* if the right node is important */
insert(value);
cout << "recurse" << endl;
}
}
}
};
//print inorder
void inorder(node* rt) {
//base
if (rt == NULL) {
return;
}
inorder(rt->left);
cout << " " << rt->key << endl;
inorder(rt->right);
}
int main() {
//create a tree for a root node
Tree t(16);
t.printRootNode();
//create newNode
node n1(20);
node n2(31);
//insert the new nodes
t.insert(20);
t.insert(31);
//keep the window from closing
system("pause");
}
感谢您的帮助。
【问题讨论】:
-
抱歉,Stack Overflow 不会为您调试代码,即使该错误恰好导致 Stack Overflow 错误。见How to debug small programs?
-
如果您遵循原始
insert中递归insert(value)调用的路径,那么第二个调用将遵循相同的路径并再次递归调用自身,并且该调用将递归调用自身- 依此类推,直到你用完堆栈。您实际上并没有在递归中取得任何进展。 -
如果您插入一棵空树,您的代码没有考虑到。
-
调试提示:将
cout << "recurse" << endl;行放在之前调用insert(value);。 (更好的是,在调用之前输出“begin recurse”并在之后输出“end recurse”。)当程序崩溃时,您想知道它在崩溃时试图做什么。它成功完成的事情通常是次要的。
标签: c++ data-structures binary-tree binary-search-tree