【发布时间】:2018-10-04 13:57:10
【问题描述】:
我正在尝试通过递归调用以下命令来构建一种算法来查找节点的后继节点:
public static BTreeNode inorderFirst(BTree T) {
BTreeNode n = T.getRoot();
if (n == null)
return null;
while (n.getLeftChild() != null)
n = n.getLeftChild();
return n;
}
然后调用这个
public static BTreeNode inorderNext(BTreeNode n) {
//returns successor. if it finds one.
// TODO
// if node has a right child get its left descendant.
// otherwise get the first ancestor of which in the left sub-tree the node n is.
// if it didn't find
return null;
} // inorderNext()
我正在使用自定义导入,它具有获取getLeftChild() 的方法,等等也有getParent(),它们并不难弄清楚。如果有人对如何开始构建它有任何想法。我添加了一些我自己计划的 cmets。我只是不知道如何开始执行。我想要这个结构,因为它使测试方法更容易。
我想出了一种不使用递归使其工作的方法:
public static BTreeNode inorderNext(BTreeNode n) {
if (n.getRightChild() != null) {
BTreeNode temp = n.getRightChild();
while (temp.getLeftChild() != null)
temp = temp.getLeftChild();
return temp;
}
else {
BTreeNode temp = n;
BTreeNode par = n.getParent();
while (par != null) {
if (par.getLeftChild() == temp)
return par;
else {
temp = par;
par = par.getParent();
}
}
}
return null;
} // inorderNext()
但我仍然想知道是否有办法在这个函数上递归地使用第一个函数。
【问题讨论】:
标签: java methods binary-search-tree inorder