java - Variable value retention while recursion -



java - Variable value retention while recursion -

i have next pseudocode need update counter value if tree instance of binarytree. if tree has more children phone call method recursively & increment counter.

the issue if create counter static (which don't want to), counter values fine when pass variable input method (as mentioned below) value 1. wrong here?

//pseudo code public static int test(tree) { integer count = 0; homecoming testtreereccounts(tree, count); } private static integer testtreerecursivecounts(tree, integer count) { if (tree instanceof binarytree) { count++; (node node :tree.getchild())) { testtreerecursivecounts((tree)node, count); } } homecoming count; }

the problem integer immutable, moment count++, count point different object.

the process : count -> unboxing -> increment value 1 -> auto boxing (which created new object).

that's why, first object value 1 return.

also note using integer instead of primitive int slow downwards performance needs autoboxing/unboxing continuously.

this problem can fixed doing this:

private static int testtreerecursivecounts(tree) { int count =0; if (tree instanceof binarytree) { count++; (node node :tree.getchild())) { count += testtreerecursivecounts((tree)node); } } homecoming count; }

java recursion

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -