0

Creating the node

       
       class Node{
           int data;
           Node left;
           Node right;
           Node(int data){
                   this.data = data;
                   left = null;
                   right = null;
           }
       }

Creating the tree

        //create tree
        class Tree{
            Node root = null;
            void insert(Node temp, int data){
                Node NewNode = new Node(data);
                if(temp == null){
                     temp = NewNode;
                }
                else{
                    if(data<temp.data){
                        insert(temp.left,data);
                    }
                    else{
                        insert(temp.right,data);
                    }
                }
            }
        }

Main function

        
        public class test{
            public static void main(String[] args) {
                Tree t = new Tree();
                t.insert(t.root,3);
                // t.insert(t.root,1);
                System.out.println(t.root.data);
                }
        }

Upon running I get t.root is null. I don't understand why. Need some help. I am passing t.root as temp, so when temp gets modified doesn't that mean t.root does too?

vade
  • 53
  • 1
  • 1
  • 4
  • 2
    Java is pass-by-value, so the assignment to temp in your insert() function does nothing. – tgdavies Jul 27 '20 at 05:57
  • Alright, then why does it work with arrays? When I pass an array into a function and modify it, I get the changed array in the output without returning it. @tgdavies – vade Jul 27 '20 at 06:11
  • @vade because you modify the array object, not array pointer – mangusta Jul 27 '20 at 07:43

0 Answers0