【问题标题】:Least common ancestor search in binary tree non recursive version - Java二叉树非递归版本中的最小公共祖先搜索 - Java
【发布时间】:2014-12-21 14:26:14
【问题描述】:

我正在搜索一种非递归算法版本,用于在用 Java 编写的已排序二叉树中查找最小共同祖先。 我发现的一切都只是递归版本(即使在 stackoverflow 和其他网站上)。

有人可以写或指导我使用非递归版本(使用 while 循环)吗? 如果这个版本在时间复杂度方面效率更高,还要写?

【问题讨论】:

    标签: java non-recursive least-common-ancestor


    【解决方案1】:

    刚好看到这个早已被遗忘的问题。

    你的意思是,如果给你一棵树:

           A
       B       C
     D   E   F   G
    H I J K L M N O
    
    commonAncestor(L,G) = C
    commonAncestor(H,O) = A
    commonAncestor(B,H) = B
    

    类似的东西?

    提供2种方法(都假设提供的节点在树中):

    如果有到父级的链接(即您从 B 指向 A),那么解决方案很简单,类似于查找相交的链表:

    找到Node1和Node2的深度,假设深度是D1D2。找出D1D2 之间的区别(假设d)。有指向 Node1 和 Node2 的指针(假设 p1 和 p2)。对于深度较高的节点,导航到第 d 次父节点。此时,p1p2 将在祖先下方具有相同的深度。只需一个简单的循环即可将p1p2 导航到父级,直到您点击p1 == p2 的节点。


    如果节点中没有父链接,则可以迭代导航树:

    currentNode = root;
    while (true) {
        if (currentNode == node1 
                || currentNode == node2 
                || (currentNode > node1) != (currentNode > node2) ) {
            break;  // current node is the common ancestor, as node1 and node2 
                    // will go to different sub-tree, or we actually 
                    // found node1/2 and the other node is its child
        } else if (currentNode > node1) {
            currentNode = currentNode.left;
        } else { // currentNode < node1/2
            currentNode = currentNode.right;
        }
    }
    
    // currentNode will be the answer you want
    

    基本思想是,假设它是一棵二叉搜索树,如果两个节点都大于/小于当前节点,它将转到同一个子树。所以共同祖先是两个值传给不同子节点的节点,即当一个小于当前节点而另一个大于当前节点时。

    【讨论】:

    • 如果每个节点没有都有父链接,是否可以提出迭代解决方案?如果是,请更新您的答案,说明我们该怎么做。
    • @AnV 我回答的最后一部分是按照您的要求进行操作。不清楚的部分是什么?
    • @AnV 添加了一些额外的解释。希望它能给你更好的主意
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2012-01-16
    • 2020-08-16
    • 1970-01-01
    • 2011-07-28
    相关资源
    最近更新 更多