-1

I am traversing a Tree and wanna know how does Recursion works internally in Trees because the code looks easy but when i debug my code i get confused that how is it working as i don't have a clear understanding of Working of Recursion, So can you explain ? Look at my code in c#

public static void Traverse(Node root)
    {
       if (root == null) return;
       Console.WriteLine(root.data);

       Traverse(root.left);
       Traverse(root.right);
    }
  • 3
    Think of the state/context of a method call as a piece of paper. When a method call is made, get a fresh sheet of paper and put it on top of the stack of the ones you already have. Then, on the top of the paper write all the parameters to the method and their values, and then make room on the paper for all the local variables. Go through the method and adjust variables on the paper as necessary. If the method calls another method, get a fresh sheet of paper and repeat. When a method returns, remove and discard its piece of paper. Think through this mental model and see if that helps. – Lasse V. Karlsen Aug 31 '20 at 06:37
  • 2
    Does this answer your question? [Understanding recursion](https://stackoverflow.com/questions/717725/understanding-recursion) – JonasH Aug 31 '20 at 06:51

1 Answers1

0

When I try to solve problems with a binary tree, I find that it helps to keep track of exactly when a certain node is entered and existed (when is it pushed to and popped from the call stack). This is similar to Lasse V. Karlsen's suggestion, but done in directly in the code. Any other code that you would use for a task (such as swapping the left and right children, collecting the sum of all visited nodes etc.) would have to happen between the two logs, and should probably have their own logs so you can see on exactly which node your error may have occurred. For example:

static ArrayList results = new ArrayList();

public static void Traverse(Node root)
{
    if (root == null)
       return;

    Console.WriteLine("Entering", root.data);

    results.Add(root.data);
    Console.Write("Current Results: ");
    foreach(int i in results) {
        Console.Write(i + " ");
    }
    Console.WriteLine("");

    Traverse(root.left);
    Traverse(root.right);

    Console.WriteLine("Exiting", root.data);
}