如何建模Patricia-Trie图

时间:2015-11-18 18:07:33

标签: java graph

我正在尝试为Patricia Trie数据结构实现插入方法。因此,如果我插入字符串aba,那么字符串abc我将在屏幕截图中得到以下特里结果。 enter image description here

我已尝试过这段代码,但我不知道如何将图形建模为输出,如何在不使用node1,node2,node3等的情况下根据需要创建多个节点?

Particia class:

package patriciaTrie;

import java.util.Scanner;

public class Patricia {

    private Node root;
    private Node parent;
    private Node node1;
    private Node node2;

    // create a new node
    public Patricia() {
        root = null;
        parent = null;
    }

    // inserts a string into the trie
    public void insert(String s) {
        if (root == null) {
            root = new Node(s, "o-");
            parent = new Node("-o");
        } else {
            insert(root, s);
        }

    }

    private void insert(Node root, String s) {
        int len1 = root.edge.length();
        int len2 = s.length();
        int len = Math.min(len1, len2);
        for (int index = 0; index < len; index++) {
            if (s.charAt(index) != root.edge.charAt(index)) {

                // In case the string are not equal, then split them.
                String samesubString = s.substring(0, index);

                String substringSplit1 = root.edge.substring(index);
                String substringSplit2 = s.substring(index);

                 root.edge = samesubString;
                 node1 = new Node(substringSplit1, "-o");
                 node2 =  new Node(substringSplit2, "-o");

                System.out.println(root.value + root.edge + node1.value +node1.edge + node2.value + node2.edge);

            } else {
                System.out.println("They are the same - " + index);
            }

        }

    }

    public static void main(String[] args) {
        Patricia p = new Patricia();
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            String op = s.next();
            if (op.equals("INSERT")) {
                p.insert(s.next());
            } 

        }

    }

}

节点类:

package patriciaTrie;

public class Node {

    String edge;
    String value;


    Node(String edge, String value) {
        this.edge = edge;
        this.value = value;
    }

    Node(String value){
        this.value = value;

    }

}

1 个答案:

答案 0 :(得分:0)

使用数组或关注符列表,而不是仅使用一条边。 在图表中通常使用跟随者边缘列表,这对于特里图来说并不特别。

要构建Patricia trie,请使用Node类simillar:

public class TrieNode {
    String value;
    // The outgoing (downstream) neighbour nodes
    List<TrieNode> next; // probably LinkedList

    /** Default Constructor with value */
    public TrieNode(String value) {
       this.value = value
    }
}

一旦构建完成,您可以使用更少的内存转换为只读图形(尝试通常用于在运行时不再更改的字典)

最终有一个低内存消耗trie,它使用数组而不是List。 List总是使用比数组更多的内存。

public class TrieNode {
    String value;
    TrieNode[] next;
}

在您的示例中,您可以构建图表:

TrieNode nodeRoot = new TrieNode ("ab");
TrieNode nodeLeft = new TrieNode ("a");
TrieNode nodeRight = new TrieNode ("c");
nodeRoot.next.add(nodeLeft);
nodeRoot.next.add(nodeRight);