【问题标题】:Tree,Nodes,Type of Trees树,节点,树的类型
【发布时间】:2013-02-10 15:13:11
【问题描述】:


我想创建一棵树来检测插入是否是字符类型的对象,它将比较每个对象并决定插入的位置[右或左],(我知道它可以通过 ascii 表中的位置检测),如果插入是 int 的对象,它将执行相同的操作。
我的问题:
1.我需要创建树并同时设置一个比较器(例如,如果它是一个字符树,它将是一个检查字符的 Chars_comperator 并且他实现了比较器(java)。? 2. 我的代码现在只适用于 int。因为我将对象转换为字符串,然后转换为 int,毕竟我比较并决定在哪里插入,这就是我需要做的吗?还是有另一种方法可以处理各种对象? 这是我的代码以及我如何创建树,

树类

public class tree {

bNode root;
public tree() {
    this.root = null;
}
public boolean isEmpty(){
    return root==null;
}
public void insert(Object data)
{
    if(isEmpty())
        this.root = new bNode(data);
    else
        this.root.insert(data);

   }
 }


bNode 类

public class bNode {
 protected Object data;
 protected bNode left;
 protected bNode right;


public bNode(Object data) {
    this.data = data;
    this.left = null;
    this.right = null;
}

public void insert(Object data){

    if(Integer.parseInt(data.toString())<Integer.parseInt(this.data.toString())){
        if(this.left==null)
             this.left = new bNode(data);
        else 
            this.left.insert(data);

    }
    else{
        if(this.right==null)
             this.right = new bNode(data);
        else 
            this.right.insert(data);



    }
}

主类

public class Main {

/**
 * @param args
 */
public static void main(String[] args) {
    tree x = new tree();
    char a = 'G';
    x.insert(a);
    x.insert(60);
    x.insert(40);
    x.insert(30);
    x.insert(59);
    x.insert(61);
    x.root.printTree(x.root);


}

}
谢谢!

【问题讨论】:

    标签: java binary-tree


    【解决方案1】:

    您可以在insert() 中传递Comparable,而不是传递一个对象。 Integer、String等标准类型已经实现了Conparable接口。

    而不是使用if (a &lt;b) 你调用

    compareTo(a,b);
    

    参见 Comparable 的 java 文档。

    如果出于任何原因,您想保留将Object 传递给insert(),您也可以不使用toString,而是通过检查对象的类,然后进行强制转换来解决这个问题:

    if (object instanceof Integer) {
        int val = ((Integer) object).intValue();
        // now compare 
    } else if (object instance of String) {
         String val .....
        // use val.compareTo()
    }
    

    【讨论】:

    • 如果我创建树例如 BinaryTree x = new BinaryTree(comp) 并且 comp 是 Comparator comp = new IntegerComparator,所以现在我确定树将是一个 int 树,所以所有检查将在 int 上,然后我不需要问所有问题,(instanceof..),我的意思是我真正想要的是创建一个实现比较器的函数,每个函数检查另一件事,它就像 instanceof,对于例如,如果我创建了一个 IntegerComparator,我知道每个对象都会通过 integercomparator 的 compareTo。我认为这样做更有效。不是吗?
    • 不,只是 new BinaryTree();否则,您必须阅读有关泛型的更多信息。但是插入(Comparable comp);使用可比较的
    • 如果我想将对象存储为字符,我按原样插入?
    • Character 是 char 的 java 对象表示
    猜你喜欢
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2016-06-08
    • 2010-12-09
    • 2016-02-16
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多