添加到二叉搜索树,返回一个布尔值

时间:2013-10-09 23:07:51

标签: java

我设法使用递归正确添加节点。

我在尝试保持计数时遇到了问题,我的递归方法在添加节点之前返回false(多次)。看起来它可以工作而不会在最后返回false但是java不喜欢它。

我该如何解决这个问题?

这是(psuedo-ish)代码:

来自set class的

if(root.add(value))
    count++
    return true
return false

if(root.add(value)) count++ return true return false

来自节点类的

    public boolean add(item value) {
    if(this == value) //check if it already exists
        return false;
    } else {
        if(this.left < value)
            if(this.left != null)
                this.left.add(value)
            else
                this.left = new Node(value)
                return true
        if(this.right > value)
            if(this.right != null)
                this.right.add(value)
            else
                this.right = new Node(value)
                return true
    }
    return false
    }

2 个答案:

答案 0 :(得分:2)

返回递归调用返回的内容吗?

public boolean add(item value) {
if(this == value) {
    return false
} else if(this.left < value) {
    if(this.left != null) {
        return this.left.add(value)
    } else {
        this.left = new Node(value)
        return true
    }
} else { //if(this.right > value)
    if(this.right != null) {
        return this.right.add(value)
    } else {
        this.right = new Node(value)
        return true
    }
}
}

顺便说一句,即使这是伪代码;如果(afaict)有点不正确?您正在检查左侧节点是否小于要添加的值,如果是这样,您将值添加到左侧节点...如果我没有弄错,您通常会添加较小的值和较高的值,因此您可能需要交换那个。 (我假设你的代码中的代码是正确的。)

答案 1 :(得分:0)

首先,您确定,问题不在于您的格式错误吗?由于您的代码,这是正确的格式。如您所见,if (this.right > value)永远不会到达......

public boolean add(item value) {
    if (this == value) {  //check if it already exists
        return false;
    } else {
        if (this.left < value) {
            if (this.left != null) {
                this.left.add(value);

            } else {
                this.left = new Node(value);
            }
        }
        return true;
        if (this.right > value) {
            if (this.right != null) {
                this.right.add(value);

            } else {
                this.right = new Node(value);
            }
        }
        return true
    }
    return false
}