Niceguy65
JCHJava Community | Help. Code. Learn.
•Created by Niceguy65 on 4/24/2025 in #java-help
I need help understanding a part of recursion for a binary search tree.
Hello I basically need to implement a recursive function for insertion of a binary tree. I already implemented the chunk of insertion function (wether it's largest or smaller than root) but there's an aspect of confusion.
public void insert(E data) {
root = insert(root, data);
}
private Node<E> insert(Node<E> value, E data) {
if(value == null) {
return new Node<E>(data);
}
else if (data.compareTo(value.data) > 0 ) {
value.right = insert(value.right, data);
}
else if(data.compareTo(value.data) <= 0) {
value.left = insert(value.left, data);
}
return value;
}
The problem I have is this line:
public void insert(E data) {
root = insert(root, data);
}
Is the root actively changing? My partner tried explaining to me how it doesn't change except for the first root.
let's say I want to insert ten and the root is null, the root will always be 10. Is this right?
Thank you.7 replies