【问题标题】:How to find successor for a given node BST如何找到给定节点 BST 的后继节点
【发布时间】: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


    【解决方案1】:

    您的代码将类似于以下内容:

    if(n.getLeftChild() != null)
            inorderNext(n.getLeftChild());
        System.out.print(n.data);
        if(n.getRightChild() != null)
            inorderNext(n.getRightChild());
    

    【讨论】:

    • 我应该递归使用inorderFirst来完成获取后继者并返回的任务。
    • 你的 inorderFirst 必须要取一棵树吗?取一个特定节点而 inOrder 取树是有意义的。
    • 我不应该以任何方式改变方法的形状或形式。
    • 我确实找到了一种无需递归的方法,但仍然想知道是否有办法在其中使用它。
    • 在这种情况下,我认为递归不会起作用。这没有意义,至少对我而言。
    猜你喜欢
    • 2013-01-16
    • 1970-01-01
    • 2018-01-31
    • 2022-01-08
    • 1970-01-01
    • 2021-11-17
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多