在C ++中返回对象(二叉树)

时间:2013-11-17 02:54:28

标签: c++ oop object pointers tree

免责声明:这是一项作业。我希望指向正确的方向(没有双关语),而不是直接的代码解决方案。

我正在尝试实现一个最大赢家树(一个二叉树,其中节点的值是其子项值的最大值,因此根最终具有所有底部叶子的最大值)。我当前的MaxWinnerTree初始化一个满-1秒的树,就像稍后要插入值的占位符一样。

MaxWinnerTree.cpp

#include "MaxWinnerTree.h"

MaxWinnerTree::MaxWinnerTree(int elements)
{   
    int size = 1;
    while (size<elements)
        size = size * 2; //gets closest power of 2 to create full bottom row

    *a = new Node[size];
    for (int i = (2*elements-1); i>0; i--)
    {
        if (i > elements-1) //leaf
        {   
            //Create new nodes with data -1, store pointer to it in array
            *a[i] = (newNode(i,-1,NULL,NULL,NULL));
        }

        else    // not leaf
        {   
            //Create node with data = max of children, store pointer
            *a[i] = newNode(i,-1,a[i*2],a[i*2 +1], NULL); //create
            a[i]->data = max(a[i*2]->data, a[i*2+1]->data); //gets max
            a[i]->right->parent = a[i];
            a[i]->left->parent = a[i];


        }
    }

}

Node MaxWinnerTree::newNode(int key, int data, Node *left, Node *right, Node *parent)
{
    Node *n = new Node;
    key = key;
    data = data;
    left = left;
    right = right;
    parent = parent;

    return *n;
}

在我的Main中,我尝试创建一个MaxWinnerTree对象来对(插入等)执行操作,但我知道我这样做的方式是不正确的。我的MaxWinnerTree方法没有返回值,我创建的唯一对象是一个数组,然后是链接的节点。当我输入这个时,我会回去尝试将链接列表作为我的树返回并从那里开始,但这是我应该进入的方向吗?

Main.cpp的

    int main (){
    bool quit;
    int command, elements, binSize;
    cout<<"Welcome to assignment 6!"<<endl;

    while (!quit)
    {
        cout<<"Choose an option for the test: 1-> First fit, 2-> Best Fit, 3-> Quit"<<endl;
        cin>>command;

        if(command==1)
        {
            cout<<"First Fit!";
            cout<<"Enter number of objects: ";
            cin>>  elements;
            cout<<"\n Enter capacities of bins: ";
            cin>>  binSize;
            cout<<"\n";



MaxWinnerTree* tree = new MaxWinnerTree(elements); //Throws x86 error, also throws error when not decared as a pointer
            tree->insert(7);
                        //Irrelevant rest of non-applicable code

从本质上讲,在调用构造函数后,我需要做些什么才能获得可以操作的树对象?

另外:我对指针感到不稳定,所以如果看起来不好或做不好,请告诉我。

0 个答案:

没有答案