Understanding Binary Search Tree Counting

Sean2148 :

I am having trouble understanding how this Binary Search Tree method is counting nodes, I have looked at many examples online, however I cannot find one which will explain exactly what is happening.

Here is an example:

public int nodes() {
    int leftNodes = 0;

    if (left != null) {
        leftNodes = left.nodes();
    }
    int rightNodes = 0;

    if (right != null) {
        rightNodes = right.nodes();
    }
    return leftNodes + rightNodes + 1;
}

This is how I am understanding the process of this method, and maybe someone can help me understand where I'm going wrong.

  1. The method is called from outside of itself from a BTS Object; "tree.nodes() etc".
  2. int leftNodes is declared and set to 0.
  3. If there is a left node (assume there is), then the value of leftNodes will be assigned to the return value of the call to nodes();
  4. The recursive call will go through the nodes method again, assigning leftNodes to zero again.

So what I don't understand is where is the leftNodes variable being incremented? It seems like it's just recursing through the method again but the value doesn't change, and from how I see leftNodes and rightNodes will always be 0.

I found another example of BTS counting, this one using C++

int CountNodes(node*root)
{
if(root==NULL)
    return 0;
if(root->left!=NULL)
{
    n=n+1;
    n=CountNodes(root->left);
}
if(root->right!=NULL)
{
    n=n+1;
    n=CountNodes(root->right);
}
return n;
}

I find this method much easier to follow, as n is clearly being incremented everytime a node is found.

My question is how is the leftNodes/rightNodes value being incremented in the recursive call?

Eran :

You should think about the end of the recursion.

Suppose you have a single node with no children.

Both left and right would be null, so you will make no recursive calls.

You'll return

leftNodes + rightNodes + 1; // 0 + 0 + 1 == 1

Now, suppose you have a simple tree that consists of a root, a left child and a right child.

When you call nodes() for the root of that tree, both left and right are not null, so we'll call both left.nodes() and right.nodes(). Since both the left and right children are leaf nodes (i.e. they have no children), the recursive calls for both will return 1, as explained above.

Therefore, when the recursive calls return, we'll return

leftNodes + rightNodes + 1; // 1 + 1 + 1 == 3

which is the number of nodes in our tree.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114641&siteId=1