Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ++i and i = 1 in a recursive function

I was trying to write a toString method with preordertraverse. Here are two functions. In preOrderTraverse there are two different outputs when I write ++depth and depth + 1.

public String toString()
{
    StringBuilder sb = new StringBuilder();
    preOrderTraverse(root, 1, sb);
    return sb.toString();
}
private void preOrderTraverse(Node<E> node, int depth, StringBuilder sb)
{
    for(int i = 1; i < depth; ++i)
        sb.append("      ");
    if(node == null)
        sb.append("null\n");
    else
    {
        sb.append(node.toString());
        sb.append("\n");
        preOrderTraverse(node.left,depth + 1, sb);
        preOrderTraverse(node.right,depth + 1,sb);
    }
}

This gives me this

  50
        30
              null
              null
        70
              null
              null

If I write this

preOrderTraverse(node.left,++depth, sb);           
preOrderTraverse(node.right,++depth,sb);

I get this one

  50
       30
            null
                 null
            70
                 null
                      null

Why is that happening?

like image 307
Thunfische Avatar asked Sep 12 '26 22:09

Thunfische


2 Answers

++depth returns the value after incrementing the value. If you have two commands that increment a value, then that value will change between the two commands.

preOrderTraverse(node.left,  ++depth, sb);           
preOrderTraverse(node.right, ++depth, sb);

is roughly equivalent* to this:

depth = depth + 1;
preOrderTraverse(node.left,  depth, sb);
depth = depth + 1;           
preOrderTraverse(node.right, depth, sb);

* it's not exactly equivalent at least because the operation is evaluated just after node.left and before the evaluation of sb (assuming the Java interpreter follows a left-to-right rule for function argument evaluation).

like image 84
gringer Avatar answered Sep 14 '26 11:09

gringer


In

preOrderTraverse(node.left,depth + 1, sb);
preOrderTraverse(node.right,depth + 1,sb);

both recursive call get the same value for the 2nd argument, since depth + 1 doesn't change the value of the local variable depth.

In

preOrderTraverse(node.left,++depth, sb);           
preOrderTraverse(node.right,++depth,sb);

The second recursive call is passed a value larger by 1 than the value passed to the first call, since ++depth increments the value of the local variable depth.

The former seems to be the correct way.

like image 40
Eran Avatar answered Sep 14 '26 11:09

Eran