Search code examples
javaoopbinary-treeroot-node

Unable to get root node value from True. Instead gives the last nodes' value


I have a public class Q5 which has a nested private static class BinTree. In main I create q5 object and give 3 nodes to add to the tree.

When I try to get the value of the root it returns the value of the last node.(here it should be returning 1 instead returns 3)

public class Q5 {

private static BinTree root;



public Q5(int ... args) 
{
    BinTree binTreeLeftChild,binTreeRightChild,root;


    root = new BinTree();       
    binTreeLeftChild = new BinTree();
    binTreeRightChild = new BinTree();


    root.value  = args[0];
    binTreeLeftChild.value = args[1];
    binTreeRightChild.value = args[2];

    root.left = binTreeLeftChild;
    root.right = binTreeRightChild;


}


private static class BinTree
{
    private static BinTree left;
    private static BinTree right;
    private static int value;

    public BinTree() 
    {
        // TODO Auto-generated constructor stub
        left = null;
        right = null;
        value = 0;
    }
}


public static void main(String[] args) 
{


    Q5 q5 = new Q5(1,2,3); 


    System.out.println(q5.root.value);



}

Solution

  • You need to remove the static identifiers in BinTree otherwise all objects of that class will share the same values.
    In Q5(int ... args) you have a private variable which is shadowing the class variable root. You need to remove that too.
    Corrected code:

    public class Q5 {
        private static BinTree root;
    
        public Q5(int ... args) {
            BinTree binTreeLeftChild,binTreeRightChild;
            root = new BinTree();       
            binTreeLeftChild = new BinTree();
            binTreeRightChild = new BinTree();
            root.value  = args[0];
            binTreeLeftChild.value = args[1];
            binTreeRightChild.value = args[2];
            root.left = binTreeLeftChild;
            root.right = binTreeRightChild;
        }
        private static class BinTree{
            private  BinTree left;
            private  BinTree right;
            private  int value;
            public BinTree() {
                // TODO Auto-generated constructor stub
                left = null;
                right = null;
                value = 0;
            }
        }
    ...
    }