首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >二叉树问题的isEmpty方法

二叉树问题的isEmpty方法
EN

Stack Overflow用户
提问于 2012-02-25 21:46:26
回答 2查看 7.7K关注 0票数 1

我试图为二叉树编写isEmpty方法,但我遇到了问题。这就是我所用的方法。

代码语言:javascript
运行
复制
public boolean isEmpty(){
if(root == null) return true;
else return false;
}

当我只添加一个元素,然后删除这个元素,并调用isEmpty时,我不会得到true,而是false。

我的执行有什么问题吗?

这就是删除方法:

代码语言:javascript
运行
复制
  /**
    * Internal method to remove from a subtree.
    * @param x the item to remove.
    * @param t the node that roots the tree.
    * @return the new root.
    * @throws ItemNotFoundException if x is not found.
    */
    protected BinaryNode<AnyType> remove( AnyType x, BinaryNode<AnyType> t )
    {
    if( t == null )
    throw new ItemNotFoundException( x.toString( ) );
    if( x.compareTo( t.element ) < 0 )
    t.left = remove( x, t.left );
    else if( x.compareTo( t.element ) > 0 )
    t.right = remove( x, t.right );
    else if( t.left != null && t.right != null ) // Two children
    {
    t.element = findMin( t.right ).element;
    t.right = removeMin( t.right );
    }
    else
    t = ( t.left != null ) ? t.left : t.right;
    return t;
    }

这是remove方法使用的removeMin方法:

代码语言:javascript
运行
复制
        /**
         * Internal method to remove minimum item from a subtree.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws ItemNotFoundException if t is empty.
         */
         protected BinaryNode<AnyType> removeMin( BinaryNode<AnyType> t )
         {
         if( t == null )
        throw new ItemNotFoundException( );
        else if( t.left != null )
        {
        t.left = removeMin( t.left );
        return t;
        }
        else
        return t.right;
        }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-25 21:52:25

检查删除元素代码。通常比代码查找删除节点的父节点并将其设置为空对应的引用。对于最后一个元素,它必须设置为空root变量。

票数 0
EN

Stack Overflow用户

发布于 2012-02-25 22:28:16

remove(AnyType x, BinaryNode<AnyType> t)方法使用X元素搜索节点,并使用removeMin方法(如果它有两个子节点)或左或右子节点替换它的一个子节点。您的公共删除方法可能如下所示:

代码语言:javascript
运行
复制
public boolean remove(AnyType x) {
    try {
        BinaryNode<AnyType> node = remove(x, root);
        if (node != null) {
            node = null;
            return true;
        }
        return fal
    } catch (Exception e) {
        //do something with the exception
        return false;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9448364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档