【发布时间】:2012-05-10 12:34:56
【问题描述】:
好吧,我有一个读取方法可以正确读取值(全部 7000),(手写 15 个值作为树结构),不会产生任何错误。
但是,当涉及到二叉树的输出时,我使用的是几个网站上所述的方法。
我得到的错误是堆栈溢出,我假设它是由于递归调用并且从未中断,但我不知道为什么这不起作用。
感谢您的帮助。
代码如下:
// Read
void BinaryTreeStorage::read(ifstream& _fin)
{
// Get first line with number of names in it
string numberOfNamesString;
getline(_fin, numberOfNamesString);
// Loop through all the names
string line;
int num = 0;
while (!_fin.eof())
{
getline(_fin, line);
if (line != "")
{
// Insert Value Here
if (root != NULL)
{
insert(line, root);
}
else
{
insert(line);
}
}
}
}
// Write
void BinaryTreeStorage::write(ofstream& _out) const
{
inorderPrint(_out, root);
}
// inorderPrint
void BinaryTreeStorage::inorderPrint(ofstream& _out, node *_root) const
{
if (_root != NULL)
{
// Inorder
inorderPrint(_out, root->left);
_out << root->nodeValue;
cout << root->nodeValue << " ";
inorderPrint(_out, root->right);
}
}
// Insert if root is null
void BinaryTreeStorage::insert(string _nodeValueIn)
{
if(root!=NULL)
insert(_nodeValueIn, root);
else
{
root=new node;
root->nodeValue=_nodeValueIn;
root->left=NULL;
root->right=NULL;
}
}
// Insert when root is not null
void BinaryTreeStorage::insert(string _nodeValueIn, node *leaf)
{
if(_nodeValueIn< leaf->nodeValue)
{
if(leaf->left!=NULL)
insert(_nodeValueIn, leaf->left);
else
{
leaf->left=new node;
leaf->left->nodeValue=_nodeValueIn;
leaf->left->left=NULL; //Sets the left child of the child node to null
leaf->left->right=NULL; //Sets the right child of the child node to null
}
}
else if(_nodeValueIn>=leaf->nodeValue)
{
if(leaf->right!=NULL)
insert(_nodeValueIn, leaf->right);
else
{
leaf->right=new node;
leaf->right->nodeValue=_nodeValueIn;
leaf->right->left=NULL; //Sets the left child of the child node to null
leaf->right->right=NULL; //Sets the right child of the child node to null
}
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!让陌生人通过检查发现代码中的错误是没有效率的。您应该使用调试器或打印语句来识别(或至少隔离)问题,然后返回更具体的问题(一旦您将其缩小到 10 行 test-case)。
-
在最后一个函数中,插入,很多没有意义。我可以看到无限递归的很多潜力。但是我没有跟踪整个事情,这就是调试器的用途。此外,您应该使用 string.empty() 检查 std::string 是否为空
标签: c++ tree binary-tree stack-overflow