我试图弄清楚如何在托管 C++ 中为学校项目创建一个二叉树类。我在非托管 C++ 和 C# 中找到了非常好的示例,因此我能够很好地理解发生了什么,但我似乎无法在托管 C++ 中弄清楚。我想知道的是:为什么我会出现堆栈溢出(见下文),这是一种明智的方法吗?这是我的课:
#pragma once
#include "stdafx.h"
#include <iostream>
#include <deque>
#include <climits>
using namespace std;
using namespace System;
using namespace System::Collections;
ref struct Node
{
int data;
Node ^parent;
Node ^left;
Node ^right;
// constructors
// default constructor
Node (){}
// constructor that takes a node with no leafs
// a constructor that accepts a new node with no children
Node(int input)
{
Node ^node = gcnew Node(input);
node->data =input;
node->left = nullptr;
node->right = nullptr;
node->parent = nullptr;
}
// method to create a new Node
Node ^newNode(int data)
{
Node ^node = gcnew Node;
node->data = data;
node->left = nullptr;
node->right = nullptr;
node->parent = nullptr;
return node;
}
// method that inserts a new node into an existing tree
Node ^insertNode(Node ^node, int input)
{
Node ^p;
Node ^returnNode;
if (node == nullptr)
{
returnNode = newNode(input);
returnNode->parent = p;
return returnNode;
}
if (input <= node->data)
{
p = node;
node->left = insertNode(node->left, input);
}
else
{
p = node;
node->right = insertNode(node->right, input);
}
return node;
}
};
当我创建一个新实例并尝试添加一个节点时,我得到一个堆栈溢出异常。
#include "stdafx.h"
#include "GenericNodeClass.h"
#include "BinarySearchTreeClass.h"
using namespace std;
using namespace System;
int main ()
{
BinarySearchTreeClass^ BTree = gcnew BinarySearchTreeClass();
Node ^newNode = gcnew Node(7);
newNode = newNode->insertNode(newNode, 6); // this just looks stupid
return 0;
}