【问题标题】:How to print a properly sorted Radix Trie如何打印正确排序的 Radix Trie
【发布时间】:2017-11-09 16:57:23
【问题描述】:

我试图打印一个正确排序的 Radix Trie,但是当我尝试这样做时,它与 DFS 一起使用,但单个字母打印在错误的位置......我做错了什么?我在递归上做错了还是我需要另一个我缺少的条件?

Ex: 

0692
072755
0
1008
1076
10

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Trie {
    static class TrieNode {
        TrieNode[] children = new TrieNode[128];
        boolean leaf;
    }

    public static void insertString(TrieNode rootNode, String s) {
        TrieNode root = rootNode;
        for (char ch : s.toCharArray()) {
            TrieNode next = root.children[ch];
            if (next == null)
                root.children[ch] = next = new TrieNode();
            root = next;
        }
        root.leaf = true;
    }

    public static void printSorted(TrieNode node, String s) {
        for (char ch = 0; ch < node.children.length; ch++) {
            TrieNode child = node.children[ch];
            if (child != null)
                printSorted(child, s + ch);
        }
        if (node.leaf) {
            System.out.println(s);
        }
    }

    public static void main(String[] args) throws IOException {
        TrieNode root = new TrieNode();

        BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in)
        );
        String line = null;
        while ((line = br.readLine()) != null) {
            insertString(root, line);
            line = null;
        }

        printSorted(root, "");
    }
}

【问题讨论】:

    标签: algorithm tree trie radix


    【解决方案1】:

    在您的 printSorted 函数中,尝试先打印叶子,因为叶子总是小于其子节点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-14
      • 2012-07-27
      • 2013-01-20
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多