【问题标题】:Find all subtrees in a tree matching a given subtree in Java在Java中查找与给定子树匹配的树中的所有子树
【发布时间】:2010-01-20 14:16:12
【问题描述】:

我正在用 Java 编写代码,该代码使用无序的有根树,其中每个节点可能有任意数量的子节点。给定一棵树 T 和一个子树 S,我希望能够找到 T 中与 S 匹配的所有子树(即 T 中与 S 同构的所有子树)。

如果 S 的节点可以映射到 T 的节点,使得 S 的边映射到 T 中的边,则 T 的子树与 S 同构。

A previous question 被问及如何查找树是否包含另一个子树,但是我希望能够在 T 中找到与 S 匹配的 ALL 子树。此外,我希望能够从 T 中每个匹配中的每个节点映射到 S 中的相应节点。

也就是说,当找到匹配项时,它不应该简单地作为指向 T 中与 S 匹配的树的根节点的指针返回,而应该以指针对列表的形式返回匹配项到节点 [(T1,S1),(T2,S2),...(Tn,Sn)] 使得 T1 是指向 T 中的一个节点的指针,该节点映射到子树中的节点 S1 等等。

也可以简单地返回一个值对列表,因为树 T 和子树 S 中的每个节点都有一个与之关联的唯一整数标识符。

例如:

给定树T如下:

    a
   / \
  b   c
 / \  
d   e

和子树 S 为:

    x
   / \
  y   z

应返回以下匹配列表:

[(a,x),(b,y),(c,z)] [(b,x),(d,y),(e,z)]

唯一匹配是由 T 中的节点集确定的,不是 T 和 S 中的节点之间的映射。

所以下面的匹配:

[(a,x),(b,z),(c,y)]

被认为与

重复

[(a,x),(b,y),(c,z)]

因为它们具有来自 T (a,b,c) 的相同节点集,所以应该只返回一个匹配项。

再举个例子,给定树T:

    a
   /|\
  b c d

和子树 S:

  x
 / \  
y   z

应返回以下匹配列表:

[(a,x),(b,y),(c,z)] [(a,x),(b,y),(d,z)] [(a,x),(c,y),(d,z)]

谁能给出如何做到这一点的任何示例代码?

编辑(关于 Chris Kannon 的评论):

我在想你想要有人编码 你的答案?你走了多远 得到?你写了什么代码? – 克里斯·坎农 1 小时前

我有以下代码,当运行时,它会建立一个指向树中节点的指针列表 (matchesList),其中子树的根节点与给定的子树匹配。但是,可能有多个子树以同一节点为根,目前每个节点最多只能添加一次到matchesList,而不管有多少匹配项在那里根。

此外,我无法弄清楚如何在子树中的节点和原始树中找到的匹配节点之间建立上述映射。

package Example;

import java.util.LinkedList;
import java.util.Vector;

public class PartialTreeMatch {
    public static void main(String[] args) {
        NodeX testTree = createTestTree();
        NodeX searchTree = createSearchTree();

        System.out.println(testTree);
        System.out.println(searchTree);

        partialMatch(testTree, searchTree);
    }

    static LinkedList<NodeX> matchesList = new LinkedList<NodeX>();

    private static boolean partialMatch(NodeX tree, NodeX searchTree) {
        findSubTreeInTree(tree, searchTree);
        System.out.println(matchesList.size());
        for (NodeX n : matchesList) {
            if (n != null) {
                System.out.println("Found: " + n);
            }
        }

        return false;
    }

    private static NodeX findSubTreeInTree(NodeX tree, NodeX node) {
        if (tree.value == node.value) {
            if (matchChildren(tree, node)) {
                matchesList.add(tree);

            }
        }

        NodeX result = null;
        for (NodeX child : tree.children) {
            result = findSubTreeInTree(child, node);

            if (result != null) {
                if (matchChildren(tree, result)) {
                    matchesList.add(result);

                }
            }
        }

        return result;
    }

    private static boolean matchChildren(NodeX tree, NodeX searchTree) {
        if (tree.value != searchTree.value) {
            return false;
        }

        if (tree.children.size() < searchTree.children.size()) {
            return false;
        }

        boolean result = true;
        int treeChildrenIndex = 0;

        for (int searchChildrenIndex = 0; searchChildrenIndex < searchTree.children
                .size(); searchChildrenIndex++) {

            // Skip non-matching children in the tree.
            while (treeChildrenIndex < tree.children.size()
                    && !(result = matchChildren(tree.children
                            .get(treeChildrenIndex), searchTree.children
                            .get(searchChildrenIndex)))) {
                treeChildrenIndex++;
            }

            if (!result) {
                return result;
            }
        }

        return result;
    }

    private static NodeX createTestTree() {

        NodeX subTree2 = new NodeX('A');
        subTree2.children.add(new NodeX('A'));
        subTree2.children.add(new NodeX('A'));

        NodeX subTree = new NodeX('A');
        subTree.children.add(new NodeX('A'));
        subTree.children.add(new NodeX('A'));
        subTree.children.add(subTree2);

        return subTree;
    }

    private static NodeX createSearchTree() {
        NodeX root = new NodeX('A');
        root.children.add(new NodeX('A'));
        root.children.add(new NodeX('A'));

        return root;
    }
}

class NodeX {
    char value;
    Vector<NodeX> children;

    public NodeX(char val) {
        value = val;
        children = new Vector<NodeX>();
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();

        sb.append('(');
        sb.append(value);

        for (NodeX child : children) {
            sb.append(' ');
            sb.append(child.toString());
        }

        sb.append(')');

        return sb.toString();
    }
}

上面的代码试图找到所有的子图:

  A
 /|\  
A A A
   / \
  A   A

哪个匹配:

    A
   / \
  A   A

代码成功检测到存在以第一棵树的顶部节点和第一棵树的第三个子节点为根的匹配项。然而,实际上有 3 个匹配根植于顶部节点,而不仅仅是一个。此外,代码没有在树中的节点和子树中的节点之间建立映射,我不知道该怎么做。

任何人都可以就如何做到这一点提供任何建议吗?

【问题讨论】:

  • 我认为您希望有人为您编写答案?你走了多远?你写了什么代码?
  • +1 以获得很好的解释......实际上今天所有的票都没有了,但重要的是意图
  • @Chris Kannon :我已根据您的评论更新了问题并包含了迄今为止编写的代码。

标签: java tree matching subtree isomorphism


【解决方案1】:

我认为您的递归方法需要返回部分匹配的列表,而不仅仅是一个布尔值。这将大大有助于解决您的两个问题(需要返回匹配列表以及查找多个匹配项)。

递归函数的类 Java 伪代码可能如下所示:

findMatches(treeNode, searchNode) {
    if searchNode has no children {
        // search successful
        pairs = []  // empty list
        return [pairs]  // list of lists
    }
    else {
        matches = []  // empty list
        searchChild = first child node of searchNode
        searchNode2 = searchNode with searchChild removed
        // NOTE: searchNode2 is created by doing a shallow copy of just the node
        // (not it's children) and then removing searchChild from the child list.

        for each treeChild in treeNode.children {
            if treeChild.value == searchChild.value {
                treeNode2 = treeNode with treeChild removed  // also a shallow copy
                childMatches = findMatches(searchChild, treeChild)
                nodeMatches = findMatches(treeNode2, searchNode2)

                // cross-product
                for each nodeMatchPairs in nodeMatches {
                    for each childMatchPairs in childMatches {
                        fullMatchPairs = [(searchChild, treeChild)]
                            + childMatchPairs + nodeMatchPairs  // concatenate lists
                        add fullMatchPairs to matches
                    }
                }
            }
        }

        return matches
    }
}

请注意,此函数不会测试 treeNode.value == searchNode.value,或将其添加到列表中。调用者需要这样做。这个函数需要在树的每个节点上运行。

按照目前的设计,它可能使用了太多内存,但可以优化。

【讨论】:

    【解决方案2】:

    This 可能会有所帮助。

    【讨论】:

    • 谢谢。是的,我已经阅读了关于树同构的那些注释和关于子树同构的附加幻灯片(lsi.upc.es/~valiente/riga-tre.pdf)但是我无法弄清楚如何将给定的算法翻译成代码,特别是关于如何在节点之间建立映射树中匹配的子树和节点。知道怎么做吗?
    • 有人有最新的链接吗?给定的已死 (404)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多