【问题标题】:trying to add a node to a tree in java尝试在java中将节点添加到树中
【发布时间】:2013-05-03 08:44:33
【问题描述】:

由于某种原因 add(value) 函数不想工作。我应该能够使用 Node 和 TreeNode 来创建一个孩子。这不是一棵平衡的树。我尝试了 Node 和 NodeTree 并使用节点创建变量并将其添加但没有成功

public abstract class TreeNode implements Comparable<TreeNode>{
protected int value;
protected TreeNode left;
protected TreeNode right;

public abstract int getValue();
public abstract int getSize();
public abstract TreeNode getLeft();
public abstract TreeNode getRight();

public void add(int value){
    if (value >= this.value){
        if (this.right == null){
            this.right = new Node(value); //trying to put a node in the "right" 
        }else{
            right.add(value);
        }
    }else if(value < this.value){
        if (this.left == null){
            this.left = new Node(value); //trying to do the same thing here
        }else{
            left.add(value);
        }
    }
    }

    public String toString() {
        return (left.toString() + ", " +Integer.toString(this.value) + ", " + right.toString());
    }

public int CompareTo(TreeNode obj){
    if(this.value > obj.value){
        return 1;
    }else if(this.value < value){
        return -1;
    }else{
        return 0;
    }
}

//public void remove(int value) throws NotFoundException{

//}
}

【问题讨论】:

  • 您输入的是什么值?您期望会发生什么以及实际发生了什么?在构造函数中分配的值在哪里?
  • 你说你试过NodeNodeTree。你试过TreeNode吗?

标签: java tree treenode addchild


【解决方案1】:

该代码有很多问题。首先,您没有覆盖 compareTo 方法。您需要将“CompareTo”更改为“compareTo”。

其次,我不知道您是在尝试创建 TreeNode 还是 Node。 Node 是否扩展了 TreeNode?​​p>

第三,您将 TreeNode 指定为抽象类,但您将其作为普通类使用,甚至将子类设为 Node() 类。

第四和第五。这些都是次要的,但是您的 add 函数具有“if (value >= this.value){} else if (value

修复这些问题,事情就会运行得更好。不贴 Node 类就很难说是什么问题了,到处都是小bug。

【讨论】:

    【解决方案2】:

    这里提供了一个起点:http://cs.uni.edu/~holmesm/docs/Session40.pdf

    基本上,您的代码应该在一个新类中(例如 Node) 您的添加方法很接近。在 NullNode 类中设置 toString() 方法以返回空字符串 (return "";),然后在 add 方法中将 this.right == null 更改为 right.toString().equals ("")。在compareTo(...) 方法中,阅读上面的建议并将obj.value 更改为obj.getValue()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      相关资源
      最近更新 更多