Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Binary Search Tree implementation problem.!
    primarykey
    data
    text
    <p>I am developing a binary search tree in java. But i am facing certain difficulties in it. Here is the code</p> <pre><code>class Node { Node left, right; Integer data; Node(Integer d, Node left, Node right) { this.data = d; this.left = left; this.right = right; } } class BinaryTree { Node root; public BinaryTree(Node root) { this.root = root; } void insert(int d) { if(root==null) root= new Node(d, null, null); insert(root,d); } void insert(Node root, int d) { if (root == null) { root=new Node(d,null,null); } else if (d &gt; root.data) { insert(root.right, d); } else if (d &lt; root.data) { insert(root.left, d); } } void inorder(Node root) { if (root != null) { inorder(root.left); System.out.println(root.data); inorder(root.right); } } } public class BST { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = null; BinaryTree bt=new BinaryTree(null); while (!(str = br.readLine()).equalsIgnoreCase("0")) { bt.insert(Integer.parseInt(str)); } bt.inorder(bt.root); } } </code></pre> <p>The problem here i am facing is as in java there is only pass by value. I am getting the root as null in every case except the first case in which i have passed the newly created root into it. Here when i am making a recursive call to the insert function by passing the value of either left or right of the root then in the new call the new root has been created if required for it but when the function gets over it's values are not reflected to the caller function's variable. In short the problem is due to the call by value being followed by the java.</p> <p>Can anyone please suggest the solution for this problem?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload