简体   繁体   中英

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);



}

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;
        }
    }
...
}

I think the problem is your "static". Try using non-static variables for your BinTree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM