我希望在这里得到一些意见。我已经构建了一个二维二叉搜索树类。我有所有操作(插入,删除等)工作正常。我遇到了一个我似乎无法解决的问题。我目前在每个节点中都有数据成员,必须在删除路径中更新(相对高度,相应子树的极值等)。问题是,我需要我的delete方法返回一个表示成功的布尔值。意思是,如果节点不存在,则返回false。否则是真的。 我递归地解决了这个问题,所以当我从每个函数调用中走出来时,我正在更新值
了解正在发生的事情,这是删除的样子:
private boolean delete (Node n, Value val, boolean cut) {
// Base case
if(n == null) return false;
if(node to be deleted) {
// Do all sorts of swapping, recursive deletion calls
}
else {
// Move around the tree until I find a node or hit null
if(is in left subtree)
delete(t.left, val, !cut);
if(is in right subtree)
delete(t.right, val, !cut);
}
// Here is where updating happens
someUpdateFunction(n);
// Now java here is forcing me to return something, so I have to return true or false
return true;
}
所以我的问题是我总是返回true,因为这段代码总是执行。有没有人知道如何更新我的删除路径,如果节点不存在,仍然可以返回false? 感谢您的任何意见。
答案 0 :(得分:2)
private boolean delete (Node n, Value val, boolean cut) {
boolean status = false;
// Base case
if(n == null) return false;
if(node to be deleted) {
// Do all sorts of swapping, recursive deletion calls
}
else {
// Move around the tree until I find a node or hit null
if(is in left subtree){
status = delete(t.left, val, !cut);
}else if(is in right subtree){
status = delete(t.right, val, !cut);
}
}
// Here is where updating happens
someUpdateFunction(n);
return status;
}