I have a function that recursively searches a tree, looking for a certain condition to hold. If it does hold, that node in the tree should be replaced by a new sort of node. In the example code below, I call the class Tree_Node
because it acts a lot like a TreeNode
but isn't exactly the same thing. Still I hope the basic idea is familiar and clear.
public void func(Tree_Node tn) {
if (!tn.isLeaf()) {
if (tn.condition()) {
tn = new Tree_Node(x);
} else {
func(tn.getChild(name));
}
}
}
Now what I'm finding out is that tn = new Tree_Node(x)
doens't change the value of the node in the tree, and I believe this is because the command is only changing the value of the local variable tn
whereas I want to change the object stored at the location it's "pointing" to. In the tree, I want to replace this node with a different node.
As I brainstorm solutions, I come up with two options that seem theoretically do-able: Somehow have memory of what the parent node was, maybe by passing it as an argument to the function, and then I can change the child of this parent. I could also perhaps define a .parent()
method for Tree_Node
s, and then be able to call that method on tn
.
The second option that comes to mind is to somehow find the address in memory where this node is stored, and update the contents of this address. I would, for various reasons, strongly prefer to do this if it is possible and not too difficult. I've also spent some time googling "java memory address" to see if answers already exist for this, but a) don't see helpful information, and b) see a number of posts suggesting that doing this sort of thing is unsafe.
Any solutions or advice would be welcome.