CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Recursion Help

  1. #1
    Join Date
    Oct 2009
    Posts
    11

    Recursion Help

    Hey everyone. I've built binary tree using recursion and included a function to print out the sum of the level of the tree of a given input by a user. My problem isn't that my function doesn't work, but it prints out to the console each levels sum where I only want the level given from the input. For example, if this is my tree:

    1
    / \
    2 3
    / \ / \
    4 5 6 7

    it will print out:
    1
    5
    22
    where I only want it to print out 22.
    Now I see in my function why is it printing out all lines, but can't figure out a different solution. I'm using a static variable to add the total up. If you suggest using a global static variable, I already tried and doesn't work. Any suggestions would really help. The function code is below and based on the tree above as a sample tree with the input -3. Thanks a ton!

    void sumLevel(treeNode *&ptr, int input /* -3 */, static int depth /* == -1*/)
    {
    static int depthTotal = 0;
    if(input == depth)
    {
    depthTotal = depthTotal + ptr->data;
    cout << depthTotal << endl;
    return;
    }
    if(ptr->left != NULL)
    {
    sumLevel(ptr->left, input, depth - 1);
    }
    if(ptr->right != NULL)
    {
    sumLevel(ptr->right, input, depth - 1);
    }
    }

  2. #2
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: Recursion Help

    have the sumlevel function return the depthTotal rather than printing it

    Then at the place where you now call the initial sumlevel, use this return value to print it out.

  3. #3
    Join Date
    Oct 2009
    Posts
    11

    Re: Recursion Help

    Well, I actually already fixed the problem. I passed in, by reference, a variable "sum" and set it to 0, then after the function call, cout sum on the next line. Worked perfectly. Thanks though, that would work to.

  4. #4
    Join Date
    Aug 2000
    Location
    New York, NY, USA
    Posts
    5,656

    Re: Recursion Help

    Quote Originally Posted by simonsayz27 View Post
    I passed in, by reference, a variable "sum" and set it to 0...
    This actually fixes an error in your original code: it would accumulate that total over multiple calls (never resets depthTotal to 0).
    Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
    Convenience and productivity tools for Microsoft Visual Studio:
    FeinWindows - replacement windows manager for Visual Studio, and more...

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured