簡體   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