在java中查找两个节点的最不常见的祖先

时间:2013-12-06 06:05:22

标签: java tree binary-tree ancestor least-common-ancestor

我已经在stackoverflow上查看了很多其他答案,找不到任何有用的东西,我要么得到root,要么返回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());
        }
    }

1 个答案:

答案 0 :(得分:0)

我们可以使用递归的后序遍历来计算最低共同祖先, 这是我的Java实现 在这里&amp; 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,同样为右子树。当sum为2时,该节点将成为最低共同祖先的2。 告诉我,如果我错了,或者你在理解代码时遇到困难