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.
3 Replies
JavaBot
JavaBot3d ago
This post has been reserved for your question.
Hey @Niceguy65! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
dan1st
dan1st2d ago
You are always setting root to the value returned by insert if root is null, you are setting it to a newly created node for the current value otherwise you are setting it to the previous value which is equivalent to not changing it at all
JavaBot
JavaBot2d ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?