473,406 Members | 2,549 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Insert Into a Binary Tree in Java

Hello,

I am new to Java and have a question I wonder if someone could please help?
I have the following code to insert into a binary tree :

Expand|Select|Wrap|Line Numbers
  1. public void insert(int data) {
  2.       root = insert (root,data);
  3. }
  4.  
  5. /* recursive helper */
  6. private Node insert(Node node, int data) {
  7.       if (node == null)
  8.             node = new Node(data);
  9.       else if (data < node.data)
  10.             node.left = insert(node.left, data);
  11.       else
  12.             node.right = insert(node.right, data);
  13.       return (node);
  14. }
  15.  
I walked through this code and saw that when insert(Node node, int data) finally
returned from the recursion, it returned the node it just created and thus it
replaced the value of "root". But when I inserted some debugging statements to
print out the "data" of "root", I saw that the "data" of "root" never changed, which
was correct (and expected result).

I wonder if someone could tell me why the value of "root" never changed when
everytime insert(Node node, int data) was called, it returned a new "node".

Thank you very much in advance,

Akino
Jul 9 '14 #1
3 2519
The key to understand why this does not work problem is to know that Java passes objects as references and those references are passed by value.

In first function call to "Node insert(Node node, int data)";
The node is a copy of the root, and any changes made on node, only affect the temporary node variable.
The root is not affected.

http://stackoverflow.com/questions/4...-pass-by-value
Jul 9 '14 #2
Also, you need to move node to left or right to make the recursion work.
Jul 10 '14 #3
Sherin
77 64KB
Try This Code

Expand|Select|Wrap|Line Numbers
  1. public class BinarytreeInsert {
  2.  
  3.     public static void main(String[] args) {
  4.         new BinarytreeInsert().run();
  5.     }
  6.  
  7.     static class Node {
  8.  
  9.         Node left;
  10.         Node right;
  11.         int value;
  12.  
  13.         public Node(int value) {
  14.             this.value = value;
  15.         }
  16.     }
  17.  
  18.     public void run() {
  19.         Node rootnode = new Node(25);
  20.         System.out.println("Building tree with root value " + rootnode.value);
  21.         System.out.println("=================================");
  22.         insert(rootnode, 11);
  23.         insert(rootnode, 15);
  24.         insert(rootnode, 16);
  25.         insert(rootnode, 23);
  26.         insert(rootnode, 79);
  27.  
  28.     }
  29.  
  30.  
  31.     public void insert(Node node, int value) {
  32.         if (value < node.value) {
  33.             if (node.left != null) {
  34.                 insert(node.left, value);
  35.             } else {
  36.                 System.out.println("  Inserted " + value + " to left of Node " + node.value);
  37.                 node.left = new Node(value);
  38.             }
  39.         } else if (value > node.value) {
  40.             if (node.right != null) {
  41.                 insert(node.right, value);
  42.             } else {
  43.                 System.out.println("  Inserted " + value + " to right of Node " + node.value);
  44.                 node.right = new Node(value);
  45.             }
  46.         }
  47.     }
  48. }
  49.  
Output of the program

Expand|Select|Wrap|Line Numbers
  1.   Building tree with root value 25
  2. =================================
  3.   Inserted 11 to left of Node 25
  4.   Inserted 15 to right of Node 11
  5.   Inserted 16 to right of Node 15
  6.   Inserted 23 to right of Node 16
  7.   Inserted 79 to right of Node 25
  8.  
Jul 21 '20 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Jerry Khoo | last post by:
hello, everybody, i am kinda new here, nice to meet u all. Now, i am > cs students and are now facing difficult problems in understanding > what a binary tree is, how it works, and the algorithm...
7
by: abhrajit | last post by:
I'm looking for a C/C++/Java library to create a balanced binary tree data structure given a set of leaf nodes as input. A leaf node should never become an interior node. So if I wish to create...
4
by: Ken | last post by:
I have a binary tree in VB NET and insertions seem to be slow. The program receives data from one source and inserts it into the tree. The program receives data from another source and...
1
by: Andrew | last post by:
Hi, im trying to create a small function which can create a binary tree from the entries in a text file and after that we can perform all the usual operations like search, insert and delete etc....
4
by: hankssong | last post by:
Hi everyone, I'm wondering whether it's possible to construct a binary-tree using python. Since python don't have pointer, it can't dynamically allocate memory like C language. But some important...
5
by: Dragonizer | last post by:
I'm using a binary tree, and each time I insert into it, it says that there is nothing there. here is my code: #ifndef BST_H #define BST_H #include <stdlib.h> class Node{ int data;...
4
by: sake | last post by:
Hey everyone, I need a little help with my binary tree program. The purpose of this program is just an exercise for myself, but for some reason it doesn't work. It's supposed to input words "One"...
2
by: cioccolatina | last post by:
Hey guys, is there anyone who could help me..? I have file ExpressionBinaryTree.java : /** class ExpressionBinaryTree * uses a binary tree to represent binary expressions * does not...
1
by: game2d | last post by:
i know how to insert, print binary tree but how to print it like this? note that leafs and nodes will change and dont have to be same as this. ex: 6 / \ 1 7 / / \ 0 5 8
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.