【问题标题】:Unable to get root node value from True. Instead gives the last nodes' value无法从 True 获取根节点值。而是给出最后一个节点的值
【发布时间】:2018-07-27 09:33:20
【问题描述】:

我有一个公共类 Q5,它有一个嵌套的私有静态类 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);



}

【问题讨论】:

    标签: java oop binary-tree root-node


    【解决方案1】:

    您需要删除BinTree 中的static 标识符,否则该类的所有对象将共享相同的值。
    Q5(int ... args) 中,您有一个私有变量,它隐藏了类变量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;
            }
        }
    ...
    }
    

    【讨论】:

      【解决方案2】:

      我认为问题在于您的“静态”。尝试为 BinTree 使用非静态变量。

      【讨论】:

      • 是的,这是静态问题。
      猜你喜欢
      • 1970-01-01
      • 2012-12-22
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多