【发布时间】:2016-05-31 07:31:02
【问题描述】:
我想编写一个从二叉搜索树中删除节点的方法。
这是我的方法:
public void remove(Node node)
//Removes a given node and puts one of the nodes below it in its place until it reaches the end
{
if (node.left != null) //If the node to the left is not empty
{
node.value = node.left.value; //Moves up the left node to take its place
remove(node.left); //Goes to the next node
if (node.left.right == null && node.left.left == null)
node.left = null; //Removes the last node at the end of the tree after moving it up
}
else if (node.right != null)
{
node.value = node.right.value; //Moves up the left node to take its place
remove(node.right); //Goes to the next node
if (node.right.left == null && node.right.right == null)
node.right = null; //Removes the last node at the end of the tree after moving it up
}
}
问题是它只在某些情况下有效。
例如,我输入 60、70、65。(根节点为 50) 树应该看起来像
50
/ \
60
/ \
70
/ \
65
然后假设我选择删除 60。起初这似乎工作正常。 但是,如果我随后运行我信任的搜索方法,则返回 70 在它的任何指针处都没有节点。
我假设正在发生的是在 65 可以向上移动之前将 70 设置为 null。并且由于 65 在技术上不再连接到树,因此搜索方法无法找到它。
所以是这样的:
50
/ \
70
/ \
/ \
65
问题是,我不明白这是怎么发生的。特别是因为如果它的两个指针都指向null,它应该将节点设置为null,由于if语句
if (node.left.right == null && node.left.left == null)
node.left = null;
和
if (node.right.left == null && node.right.right == null)
node.right = null;
另外,如果第一个 if 语句不正确(如果 left != null),它不应该简单地继续插入“else”(并删除右边的)吗?
非常欢迎任何建议或提示。
【问题讨论】:
-
帮自己一个忙,将 BST 代码与 Swing 代码分开。为您的 BST 编写单元测试并确保其正常工作,然后将其连接到前端。
-
我不知道如何在这里制作一棵树,但拿你原来的树并将 65 放在 60 所在的位置。我认为不可能有一棵像你认为的那样的树。
-
@Marichyasana 示例的树是正确的 BST;修改后的结果不是。
标签: java tree binary-search-tree