所以我一直在学习所有关于二叉树的知识,并决定编写一个简单的程序来向我自己证明我可以将我的知识应用到工作代码中。我试图用这个代码做的事情是在一棵二叉树中添加4个数字,并按照从最小到最大的顺序输出数字。虽然,我的代码遇到了问题。当我运行代码时,Visual Studio在第29行和第59行将其分开。我相信问题与递归函数addLeaf有关,但也许是其他内容。任何建议,解决方案,或输入将不胜感激。!基本二叉树程序C++
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
struct node
{
int data;
node* left;
node* right;
};
node* root = NULL;
node* createLeaf(int data)
{
node* n = new node;
n->data = data;
n->left = NULL;
n->right = NULL;
return n;
}
void addLeaf(int data)
{
node* curr = root;
//If tree is empty, create first node
if(root == NULL)
{
root = createLeaf(data);
}
//Left(Less than)
else if(data < curr->data)
{
//Check for curr->left
if(curr->left != NULL)
{
addLeaf(data);
}
else //Adds node to left if null
{
curr->left = createLeaf(data);
}
}
//Right(greater than)
else if(data > curr->data)
{
//Check for curr->right
if(curr->right != NULL)
{
addLeaf(data);
}
else //Adds node if right is Null
{
curr->right = createLeaf(data);
}
}
else
{
cout << "The data " << data << " has already been received\n";
}
}
void printTree(node* Ptr)
{
if(root != NULL)
{
if(Ptr->left != NULL)
{
printTree(Ptr->left);
}
cout << Ptr->data << " ";
if(Ptr->right != NULL)
{
printTree(Ptr->right);
}
cout << Ptr->data << " ";
}
else
{
cout << "The Tree is empty\n";
}
}
int main()
{
int data[4] = {1, 7, 5, 4};
node* Ptr = root;
for(int i = 0; i < 4; i++)
{
addLeaf(data[i]);
}
printTree(Ptr);
system("PAUSE");
return 0;
}
你为什么不组织你的树一类,而不是自由函数和全局变量? –
你能具体说明哪一行是第29行和第59行吗?没有人会为你排队计数 –
如果你很好奇:第29和59行是空行和第一个括号。我不认为调试器会打破这些。 – roeland