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?
++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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With