0

I'm trying to understand intuitively how to create recursive functions (for anything) but mostly for traversing a tree to check if that tree meets certain criteria.

For a random example, counting the number of nodes in a Binary Tree that are not the root or the leaves? How do I go about recursively thinking about this problem and eventually coming up with a psuedocode solution? Previously, I would start a problem like this by drawing out different scenarios and creating pseudocode to account for the cases I came up with, but I felt like (and did) miss some logic here and there.

Any suggestions?

1 Answers1

1

In general, recursion is about finding a repetitive pattern and extrapolating it to a more general solution. According to Wikipedia:

"Recursion is the process of repeating items in a self-similar way.”

But it's a quite vague and unspecific definition. Let's go to the examples.


Binary tree is a highly repetitive structure. Consider this (almost) minimal example:

enter image description here

Now, imagine that you want to visit each node in that tree, assuming that you are starting in the root. It seems pretty straightforward:

visit(l_child) 
already in root   
visit(r_child) 

          already in root 
             /      \
            /        \
visit(l_child)       visit(r_child)

So basically you are:

 starting in the root → 
 visiting the left child → 
 getting back to the root → 
 visiting the right child → 
 getting back to the root. 

Take a look at another example of a binary tree:

enter image description here

As you can see there's a huge resemblance to the previous structure. Now, let's visit each coloured node:

visit(l_subtree) 
already in root     
visit(r_subtree) 

It's exactly the same pattern. Since we know how to traverse the subtrees, we can think of a more general algorithm:

inorder(node):
    if node == null:   //we've reached the bottom of a binary tree
        return 0
    inorder(node.l_child)
    do_something(node)
    inorder(node.r_child)

And that's the whole inorder traversal algorithm. I'm certain that you can figure out on your own how to write a pseudocode for preorder and postorder.

If recursion is still not intuitive to you, you can check this fractals example.

Kuba Rakoczy
  • 3,954
  • 2
  • 15
  • 16