java - Unable to set reference variable in recursive call -
i using recursive method find node in binary tree using key. when find node, set reference variable(foundnode) , return. problem when read object value still null. can help.
findgivennode(root, key, foundnode, parentstack); private boolean findgivennode(node node, int key, node foundnode, stack<node> parentstack) { if (node == null) { return false; } parentstack.add(node); if (node.getdata() == key) { foundnode = node; return true; } boolean leftreturn = findgivennode(node.getleftchild(), key, foundnode, parentstack); boolean rightreturn = findgivennode(node.getrightchild(), key, foundnode, parentstack); if (leftreturn || rightreturn) { return true; } else { parentstack.pop(); return false; } }
java doesn't pass arguments reference, passed value. read more here
let's clarify example. make key looking integer value 21
. situation @ beginning of function following:
so now, when say:
foundnode = node; // doesn't reflect outside of method
you changing value of foundnode
locally inside findgivennode()
method, doesn't apply outside method. basically, local variable called foundnode
references node want change , make local variable foundnode
reference new node statement above. change reflected inside function. function finished, local variables don't exist anymore neither local version of foundnode
. visual result:
the simple solution use wrapper function
to keep track of reference, can make simple wrapper class store reference want:
private class nodewrapper { node foundnode; nodewrapper() { foundnode = null; } }
then can create new nodewrapper
, pass function instead of foundnode
nodewrapper wrapper = new nodewrapper(); findgivennode(root, wrapper, key, parentstack);
then inside function instead of:
foundnode = node;
you say:
wrapper.foundnode = node;
this way can maintain reference throughout recursion inside nodewrapper
. meaning:
nodewrapper wrapper = new nodewrapper(); findgivennode(root, wrapper, key, parentstack); // @ point, wrapper.foundnode hold reference node need // or null if node wasn't found
on note, above method have function prototype:
findgivennode(root, key, foundnode, parentstack);
seems still used c/c++ :)
this unnecessary in java, can read this question thread reasoning behind or google it.
Comments
Post a Comment