java - 无法从 True 获取根节点值。相反,给出最后一个节点的值

标签 java oop binary-tree root-node

我有一个公共(public)类 Q5,它有一个嵌套的私有(private)静态类 BinTree。 在 main 中,我创建 q5 对象并提供 3 个节点以添加到树中。

当我尝试获取根的值时,它返回最后一个节点的值。(这里应该返回 1 而不是返回 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);



}

最佳答案

您需要删除 BinTree 中的 static 标识符,否则该类的所有对象将共享相同的值。
Q5(int ... args)中,您有一个私有(private)变量,它隐藏了类变量root。您也需要删除它。
更正后的代码:

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

关于java - 无法从 True 获取根节点值。相反,给出最后一个节点的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51554984/

相关文章:

java - 指向作为 JNA 方法参数的结构数组的指针

java - 如何使用选择列表缩短代码? Spring HTML

python - 拦截对对象属性的 __getitem__ 调用

swift - 如何在 Swift 中分配和解包可选数组对象?

c - 可以形成多少种不同的二叉树?

java - 为什么Java中不指定类或对象就可以调用setLayout()?

java - 多个按钮的ActionListener-Swing

java - 如何在 .txt 文件上写入内容?

java - 如何使用不在接口(interface)接口(interface)中的方法 i = new class();

binary-tree - 不使用递归的二叉树后序遍历