繁体   English   中英

在Java中找到两个节点的最小公祖

[英]Find least common ancestor of two nodes in java

我在stackoverflow上查看了许多其他答案,但找不到任何有效的方法,我要么获得了根目录,要么返回了node1本身,我不确定如何递归执行此操作,并且已经尝试了很多次,都结束了同样的方式。 任何帮助将不胜感激!

这是我的代码:

private static Node findLCA(Node node1, Node node2) {
    Node temp1 = node1, temp2 = node2, currentLargest = null;
    int largestDepth = 0;
    boolean found = false;
    if(node1 == null || node2 == null){
        return null;
    } else{
        while(found == false){
            if(temp1.getParent() != null && temp2.getParent() != null && temp1.getParent() == temp2.getParent() && nodeDepth(temp1.getParent()) > largestDepth){
                largestDepth = nodeDepth(temp1.getParent());
                currentLargest = temp1;
                temp1 = temp1.getParent();
                temp2 = temp2.getParent();
            } else if(temp1.getParent() != null){
                temp1 = temp1.getParent();
            } else if(temp2.getParent() != null){
                temp2 = temp2.getParent();
            }
            if(temp1.getParent() == null && temp2.getParent() == null){
                found = true;
            }

        }
        if(nodeDepth(temp1) >= largestDepth){
            return temp1;
        } else{
            return currentLargest;
        }
    }
}

我对其进行了编辑,以列出每个节点的祖先,但是我不确定如何遍历每个节点以查看列表中的元素是否匹配,因为它们通常大小不同。

这是新代码:

ArrayList<PhyloTreeNode> list1 = new ArrayList<PhyloTreeNode>();
    ArrayList<PhyloTreeNode> list2 = new ArrayList<PhyloTreeNode>();

    if(node1 == null || node2 == null){
        return null;
    } else{
        if(node1.getParent() != null){
            list1.add(node1.getParent());
            findLeastCommonAncestor(node1.getParent(), node2);
        }
        if(node2.getParent() != null){
            list2.add(node2.getParent());
            findLeastCommonAncestor(node1, node2.getParent());
        }
    }

我们可以使用递归后顺序遍历来计算最低的共同祖先,这是我的Java实现。这里给a和b提供了输入数据,我必须为其找到最低的共同祖先。

 public static int lowestcommanancestors(Node root,int a,int b){ if(root==null) return 0; int x=lowestcommanancestors(root.left,a,b); int y=lowestcommanancestors(root.right,a,b); if(x+y==2){ System.out.println(root.getData()); return 0; } if(root.getData()==a || root.getData()==b){ return x+y+1; } else{ return x+y; } } 

首先,我检查给定的输入节点是否出现在左子树中,如果是,则返回1,否则返回0,与右子树类似。当总和首次为2时,该节点将是最小的祖先。 告诉我我是错还是您在理解代码方面遇到困难

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM