java中的LCA算法(使用非二叉树)

时间:2015-11-17 10:32:33

标签: java algorithm tree lowest-common-ancestor

我使用数组编写了一个非常简单的树类。此类需要表示链接在一起的数据,但它们可以具有不同数量的连接(即,一个路径可以只有3个节点而另一个可以有10个节点)。说,我需要找出一个可能的解决方案,使用这个具有多个叶索引的类来执行LCA。 这是我到目前为止编写的代码:

public class ArrayTree {

/**
 * Tree structure
 */
private int[] t;

/**
 * The size of this database
 */
private int N;

/**
 * Creates an array tree with the given size
 * 
 * @param n
 *            the size of the array tree
 */
public ArrayTree(int n) {
    N = n;
    t = new int[N];
}

/**
 * add a new node
 */
public void addNode(int id, int parent) {
    validate(parent);
    t[id] = parent;
}


/**
 * Given an id this method will return an iterable object 
 * orderd from root to leaf
 */
public Iterable<Integer> getEntries(int id) {
    validate(id);
    List<Integer> entries = new ArrayList<Integer>();
    while (id > 1) {
        entries.add(id);
        id = t[id];
        if (id == 0) {
            return null;
        }
    }
    // Reorder entries from root to leaf
    Collections.reverse(entries);
    return entries;
}

/**
 * Private method for validating indexes
 * 
 * @param index
 *            the index
 * @throws IndexOutOfBoundsException
 *             if index > N or index < 0
 */
private void validate(int index) {
    if (index >= N) {
        String error = String.format("Index: %d - Size: %d", index, N);
        throw new IndexOutOfBoundsException(error);
    } else if (index < 0) {
        String error = "negative index";
        throw new IndexOutOfBoundsException(error);
    }
}

}

提前致谢, 欢呼声,

乔瓦尼

2 个答案:

答案 0 :(得分:1)

多节点的基本LCA算法可以做到这一点:

  • 获取每个节点的深度

  • 对于深度大于最小深度的每个节点,转换到父节点,直到所有节点都处于最小深度

  • 虽然并非所有节点都相同,但将每个节点转换为其父节点

  • 当所有节点汇聚到一个节点时,那就是LCA

我无法真正为此提供代码,因为从代码中可以看出如何识别根,这对于查找节点的深度是必要的。

答案 1 :(得分:0)

您想要找到两个叶节点的LCA,称之为 node1 node2

  • 为node1
  • 致电getEntries()
  • 为node2
  • 致电getEntries()
  • 现在遍历两个列表,直到两个列表上的节点相同
  • 列表中下一个节点不同的第一个节点是LCA。

这适用于非二叉树。