0

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_Nodes, 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.

Addem
  • 3,635
  • 3
  • 35
  • 58
  • How about returning a value, so you can replace `tn` with `func(tn)`? – Andy Turner Jan 28 '18 at 17:03
  • @AndyTurner I don't think this is a duplicate of what you linked since I'm not asking what the difference is, and I'm asking how to accomplish a specific function, which that post doesn't answer. As for returning a value, I'll try to think about how that could solve the problem. – Addem Jan 28 '18 at 17:08
  • the answer to the question "how do I change a local variable" is "change it in the context to which it is local", and the reason why that is the only option is that Java passes by value. Your only choices are to pass in a value which is internally mutable (like the parent, and some indication of the child), to store the thing you want to manipulate in a member variable (basically the same, just the mutable thing is `this`; worth avoiding because of thread safety considerations) or to use the return value. – Andy Turner Jan 28 '18 at 18:15

0 Answers0