所以我一直在學習所有關於二叉樹的知識,並決定編寫一個簡單的程序來向我自己證明我可以將我的知識應用到工作代碼中。我試圖用這個代碼做的事情是在一棵二叉樹中添加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