开发者

Where can we use "This" in Recursion method

I have a method in a static class which tries to convert a binary tree to a list

I'd like to make it recursive but I couldn't

I've implemented some other methods in my class like add(), delete(), find().

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 transfer the code from binary tree to list.

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开发者_如何学JAVA.r);
                        return(x);
                }

        }

}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜