Why doesn't Java call by reference?
When I pass root.left from add to add(data, parent), I'm not passing the reference to this object so that it gets changed, but only a kind of copy that has no reference to my root. How do I work around this? A beginner's programming language should be able to do this.
public class Tree { TNode root; Tree(){ this.root = null; } public void add(int data){ if(root == null){ root = new TNode(data); }else{ if(data < this.root.data){ add(data, root.left); System.out.println("miosty"); }else { add(data, root.right); } } } public void add(int data, TNode parent){ if(parent == null){ System.out.println("Zu"); parent = new TNode(data); }else{ if(data < parent.data){ add(data, parent.left); } else { add(data, parent.right); } } } }
Java makes calll by reference, but your design is also a little cumbersome and ‘nasty’
This should look more structurally, with recursive work being done here, but you can also implement iteratively quite similar.
P.S.: You may notice in the course of further implementation that the descent takes place as well as in the search, so that you may that adds to the use of the search.
But why does your code not work for me, there is nothing to be returned, and you will also do current = new TNode(data);
You have to imagine that you have your TNode somewhere in the store and your program has a reference to this object. If you now pass the reference as an argument in a method, a new Reference creates but shows the same object.
This means that if you create a new object and show your second reference, then nothing changes to your original object, and your first reference still shows it.
This means the code in the else block is fine at the second overcharging of “add()” but not the assignment “patent = new TNode(data) ;” .
in C, that’s so radio-to-in, why not here?
In C it would only work if you used a double pointer, e.g. “int **”. In Java it is not possible to fit a reference by reference.
However, another user wrote to you about 3 hours ago, in an answer to the same question.
Yes, you give a reference. If parent.left is NULL, you will start a new node that will be deleted directly. Apart from this, the methods are copy&paste and therefore nixht well written.
why is the directly deleted again, I tried it but not
Because there are no references to the object. It only exists within the function. Then it will be deleted when the function is finished.
what could I do differently, I want it to be so fun, in the video he also made it with the difference that he has passed root and not root.left