views:

66

answers:

2

Hi . I have a methode in a static class which try to convert bi*nar*y tre to list

I'd like to make a recusion but I couldn't

I've implemented some opertation in my class like add,delet,find.it's too easy to implement its .

Here is the code

class ARB
{
        private:
                struct BT
                {
                        int data;
                        BT *l;
                        BT *r;
                };
                struct BT *p;
       public
                ARB();
                ~ARB();
                void del(int n);
                void add(int n); 
};

    void ARB::del(int num)
{
//The code ,don't care about it 

  };  

main()
{
// 
    BTR T;
    T.add(3);
    T.add(5);

};

Here is what should we do to transfert the code from Benary tree tolist

LLC ARB::changeit()
{   LLC x;
        while(this!=NULL)
        {
            x.add(this->data); //
                if(this.l==NULL)
                {
                       x.print(); //To print the elemnts of List
                        return(x);
                }
                else
                {
                        x=changeit(this.l);
                }

                if(this.r!=NULL)
                {
                       x.~LLC();
                       x=changeit(this.r);
                        return(x);
                }

        }

}
A: 

The description of the problem is hard to follow but I noticed that you used the keywords this and static, which are generally mutually exclusive.

Any static function pertains to a class, not an object. Static functions can be called using the ARB::myStaticFunction() syntax and do not require an actual ARB object. So, this inside such a function does not refer to any object and is meaningless.

Artem
A: 

This call is meaningless:

x=changeit(this.l);

Since this refers to the ARB object that has no member called l. The same goes for this code:

this->data

You sometimes do this.data and sometimes this->data so you seem to be confused over the notion of an object pointer. Your ARB has the BT* called p which is the tree root, supposedly. You should start from it.

Also this is obviosly wrong:

x.~LLC();

Don't call the destructor of LLC explicitly!

The general algorithm for recursively placing a binary tree into a list (pseudocode):

tolist(node, list):
  if node == NULL:
    return
  else:
    tolist(node.left, list)
    list.append_to_end(node.data)
    tolist(node.right)

This assumes append_to_end of list is efficient, to make sense (this is achievable with an end pointer in the list). Also, it takes a list as an argument and modifies it. You can easily change it to have an internal recursive method that does that and an external method that creates a list, calls this method, and returns the list.

Eli Bendersky