BinarySearchTree删除整数时的删除方法出现故障 [英] BinarySearchTree remove method malfunctioning when removing integers

查看:83
本文介绍了BinarySearchTree删除整数时的删除方法出现故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从头开始编写BinaryTree结构,其中包括一个remove(Object obj)方法,用于从所述树中删除元素.它似乎对除Integer之外的所有类型均正确运行,我不知道为什么.

I wrote the BinaryTree structure from scratch, which included a remove(Object obj) method to remove elements from said tree. It seems to function correctly for every type except an Integer, and I can't figure out why.

public BinaryTree<E> remove(Object obj) {
        try{
            E value = (E)obj;
            int cmp = value.compareTo(this.value); 
            if(cmp == 0) {
                List<BinaryTree<E>> kids = children();
                if(kids.size() == 0) {
                    return new EmptyBinarySearchTree<E>();
                }
                if(kids.size() == 1) {
                    return kids.get(0);
                }
                //2 children
                BinaryTree<E> successor = ((BinarySearchTree)right).smallest();
                BinaryTree<E> result = remove(successor.getValue());
                result.setValue(successor.getValue());
                return result;
            }
            if(cmp < 0) {
                left = left.remove(value);
            }
            if(cmp > 0) {
                right = right.remove(value);
            }
        }
        catch(ClassCastException cce) {

        }
        return this;
    }

我用以下代码驱动BinaryTree,它也实现了我构建的Set:

I'm driving the BinaryTree with the following, which also implements Set that I built:

package setDriver;
import set.*;
import list.*;

public class HwTreeSetDriver
{
    public static void main()
    {
        Set <Integer> values;
        values = new TreeSet <Integer> ();


    values.add (3);
    values.add (5);
    values.add (3);



    for (int j=0; j<5; j++)
         values.add (j * 10);


    Iterator<Integer> itty = values.iterator();
    while (itty.hasNext())
        if (itty.next() % 2 == 1)
            itty.remove();              // remove odd numbers


}

}

运行驱动程序后,大小仍为6,并且该组包含3、5、10、20、30、40.

After running the driver, the size is still 6, and the set contains 3, 5, 10, 20, 30, 40.

以下是TreeSet中的remove(Object obj)方法,该方法依次调用我最初发布的remove方法:

The following is the remove(Object obj) method in TreeSet, which in turn calls the remove method I posted initially:

public boolean remove(Object obj){
    if(!contains(obj)) return false;

    tree = tree.remove(obj);
    size--;
    return true;
}

推荐答案

Java中的对象?

int不被视为对象 这是一个关于stackoverflow的问题供证明

int is not considered a object here a question on stackoverflow for proof

这篇关于BinarySearchTree删除整数时的删除方法出现故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆