Algorithm 如何表示非二叉树以及如何在该树上进行LCA?
非二叉树通常是如何表示的?一个节点可以拥有的子节点数量没有限制的树。最好使用邻接矩阵或邻接列表,假设没有循环,或者做类似于这个问题的事情-> 接下来的问题是,当您有一个n元树(这是正确的名称吗?)时,如何找到该树中两个给定节点/数据值的最不常见祖先?我所能找到的就是处理二叉树的算法,比如这个->Algorithm 如何表示非二叉树以及如何在该树上进行LCA?,algorithm,tree,least-common-ancestor,Algorithm,Tree,Least Common Ancestor,非二叉树通常是如何表示的?一个节点可以拥有的子节点数量没有限制的树。最好使用邻接矩阵或邻接列表,假设没有循环,或者做类似于这个问题的事情-> 接下来的问题是,当您有一个n元树(这是正确的名称吗?)时,如何找到该树中两个给定节点/数据值的最不常见祖先?我所能找到的就是处理二叉树的算法,比如这个-> static Node lca(Node root,int v1,int v2) { if (root == null || root.data == v1 || root.data == v2)
static Node lca(Node root,int v1,int v2)
{
if (root == null || root.data == v1 || root.data == v2) {
return root;
}
Node left = lca(root.left, v1, v2);
Node right = lca(root.right, v1, v2);
if (left != null && right != null) {
return root;
}
return (left != null) ? left : right;
}
邻接矩阵听起来是个坏主意,它将非常稀疏(大多数单元格将是空的)。通常对于
n元树
(是的,这就是它们的名称)您只需遵循与二叉树相同的策略,不同之处在于二叉树将有两个字段表示左
和右
子级:
class Node<T> {
T value;
Node<T> left;
Node<T> right;
}
int count = 0;
Node<T> temp = null;
for(Node<T> child : root.children) {
Node<T> result = lca(child, v1, v2);
if(result != null) {
count++;
temp = result;
}
}
if(count == 2) {
return root;
}
return temp;
使用父指针和/或在每个节点中存储dept,我们可以做得更好,但需要存储成本。好线程!您能否详细说明父指针和/或存储dept of nodes如何加速算法?当前的实现有O(n)个时间复杂度和O(1)个空间复杂度?对吗?谢谢
int count = 0;
Node<T> temp = null;
for(Node<T> child : root.children) {
Node<T> result = lca(child, v1, v2);
if(result != null) {
count++;
temp = result;
}
}
if(count == 2) {
return root;
}
return temp;