Trie 数据结构源码分析(源码来源 rt.jar)

先上图:
如下是 Trie 数的数据结构:
这里写图片描述
Trie 树的作用:统计,排序和保存字符串
快速查找某个单词key 所对应的 value 值(类似 Map 的功能)

(扩展的时候,可以判断某个 key 是否存在, 统计某个前缀被多少个单词占用(文章后面提到))

优点:
做查询的时候, 性能不会随着总的数据量增加而导致查询效率下降(空间换时间的思想)
(其他树形查找算法, 如二叉树查找, 性能会随着总的数据量增长而下降,而 Trie 树查找时的比较次数只跟 key 的长度有关系)

node 节点数据结构:

  /**
   * The node representation for the trie.
   * @xsl.usage internal
   */
  class Node
  {

    /**
     * Constructor, creates a Node[ALPHA_SIZE].
     */
    Node()
    {
      m_nextChar = new Node[ALPHA_SIZE];
      m_Value = null;
    }

    /** The next nodes.   */
    Node m_nextChar[];

    /** The value.   */
    Object m_Value;
  }

put()方法:

 /**
   * Put an object into the trie for lookup.
   *
   * @param key must be a 7-bit ASCII string,只处理128个字符
   * @param value any java object.
   *
   * @return The old object that matched key, or null.
   */
  public Object put(String key, Object value)
  {

    final int len = key.length();
    if (len > m_charBuffer.length)
    {
        // make the biggest buffer ever needed in get(String)
        //m_charBuffer用在 get 的时候用于装载key的字符数组,排除掉 key 过长的情况
        m_charBuffer = new char[len];
    }
    //指向根节点
    Node node = m_Root;

    for (int i = 0; i < len; i++)
    {
    //检查该节点的m_nextChar数组中是否包含key.charAt(i)该字符
      Node nextNode = node.m_nextChar[Character.toUpperCase(key.charAt(i))];

      if (nextNode != null)
      {
        node = nextNode;
      }
      else
      {
      //向 node 节点插入剩余的字符
        for (; i < len; i++)
        {
          Node newNode = new Node();
          // put this value into the tree with a case insensitive key
          //不区分大小写是为了在 get 的时候能忽略大小写
          node.m_nextChar[Character.toUpperCase(key.charAt(i))] = newNode;
          node.m_nextChar[Character.toLowerCase(key.charAt(i))] = newNode;
          node = newNode;
        }
        break;
      }
    }
    //把最终节点的旧的值return
    Object ret = node.m_Value;
    //node 节点的 value 指向传入的 value
    node.m_Value = value;

    return ret;
  }

get()方法:

public Object get(final String key)
{

    final int len = key.length();

    /* If the name is too long, we won't find it, this also keeps us
     * from overflowing m_charBuffer
     */
    if (m_charBuffer.length < len)
        return null;

    Node node = m_Root;
    switch (len)
    {
        // case 0 looks silly, but the generated bytecode runs
        // faster for lookup of elements of length 2 with this in
        // and a fair bit faster.  Don't know why.
        case 0 :
            {
                return null;
            }
//直接查询跟节点 Node
        case 1 :
            {
                final char ch = key.charAt(0);
                if (ch < ALPHA_SIZE)
                {
                    node = node.m_nextChar[ch];
                    if (node != null)
                        return node.m_Value;
                }
                return null;
            }
                    default :
            {
                key.getChars(0, len, m_charBuffer, 0);
                // copy string into array
                for (int i = 0; i < len; i++)
                {
                    final char ch = m_charBuffer[i];
                    //非 ASCII码不处理
                    if (ALPHA_SIZE <= ch)
                    {
                        return null;
                    }

                    node = node.m_nextChar[ch];
                    if (node == null)
                        return null;
                }
                return node.m_Value;
            }
    }
}

源码的数据结构是没法统计多少个单词占用了相同的前缀的.

要实现该功能, 则需要在 Node 节点中加入一个属性(如:sum), 每 put一个单词 到 Trie 树时, 所经过的字符都+1 ; 当需要统计某个前缀被多少个单词共用时, 直接读取该前缀的最后一个字符的sum 字段即可.

要使用 Trie 树判断某个 key 是否在树上, 可以在 Node 节点中加入一个boolean 标志位, 在插入每个单词的时候, 最后一个字符所在的 node 把标志位设置为 true 即可.(就实现了 set 的功能)

如果要实现 Trie 树排序的功能, 只需要先将所有 key 存入 Trie 树, 然后通过深度遍历的方式读取即可实现排序.

从源码看, Node根节点是存储数据的 , Trie对象有个属性m_Root指向最上层的 node 节点(根节点).

测试代码:

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.put("adef", "yangyang");
        trie.put("abg", "xiaochen");
        Object tem = trie.get("ABG");
        System.out.println(trie);
    } 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
数据结构》(C语言版) 算法源码及运行演示系统使用说明 一、启动演示系统 双击演示系统应用程序文件“DS_VC_ALGO.EXE”启动演示系统,出现图1所示界面。 图1 《数据结构》(C语言版)算法源码及运行演示系统主界面 二、演示系统使用步骤 除了个别算法之外,演示系统给出了《数据结构》(C语言版)书中算法对应的程序代码(CPP文件)和测试运行程序(VC++6.0的EXE文件)。通过本系统,可以显示算法的源代码以及运行结果。具体操作步骤如下: 1.选择相应章 单击演示系统界面右侧章选择按钮。 例如,要选择第6章,则单击“第6章”选择按钮。 当相应章被选择后,窗口的右侧部分将列出本章的算法选择按钮。 例如,选择第6章后,窗口的右侧部分将显示第6章中的算法6.1-6.13和6.15的选择按钮。由于书中的算法6.14和6.16只是示意性算法,故未给出源码,其按钮上的文字为灰色,处于“无效”状态。 2.选择相应章中的算法 单击窗口右侧部分所列举的本章某个算法选择按钮,被选择的算法的源码将在窗口左侧空白区域中显示。对于较长的源码,单击显示区域后,可用键盘的光标键和翻页键浏览源码。 例如,选择了第6章中的算法6.5后界面如图2所示: 图2 选择算法6.5 3.运行测试程序 单击窗口上部的“运行”按钮,将弹出运行窗口,运行所选算法的测试程序。若运行按钮为灰色,表示该算法无单独测试程序。 例如,算法6.5的测试运行窗口如图3所示: 图3 测试运行窗口 测试运行说明: 测试运行窗口显示程序的执行过程及结果。若在显示过程中出现运行窗口无法正常演示的情况,只需调节运行窗口大小即可正常显示(调节最小化按钮或窗口最大化/还原按钮“ ”)。 三、退出演示系统 使用完毕后,单击窗口右上角关闭按钮“ ”退出演示系统。 四、测试程序示例 在《数据结构》的课程教学中,各抽象数据类型的设计与实现是重要的学习和实践环节。为此,本系统只给出了各算法源码的测试程序的可执行文件。在此,给出算法6.5的测试程序示例,以供参考。 算法6.5是中序遍历线索二叉树的非递归算法,要对其源码进行测试,可首先调用算法6.6及6.7建立中序线索二叉树。以下是测试程序的源码,相关类型和辅助函数定义在文件include06.h和include06.cpp中,此略。 // test0605.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "include06.h" // 相关类型和辅助函数的定义 BiThrTree pre; // 线索二叉树遍历辅助变量 #include "algo0607.cpp" // 算法6.7源码 #include "algo0606.cpp" // 算法6.6源码 #include "algo0605.cpp" // 算法6.5源码 int main(int argc, char* argv[]) { char gl_str[64]; BiThrTree T; BiThrTree Thrt; printf("*******************************************\n"); printf("* 《数据结构》(C语言版)严蔚敏,吴伟民 *\n"); printf("* 算法6.5, 6.6 & 6.7 *\n"); printf("*******************************************\n"); srand((unsigned)time(NULL)); // 随机函数初始化 T=NULL; // 空二叉树T for (int pass=0; pass<5; pass++) { // 测试运行5次,第一次为空树 outBiThrTree(T,gl_str); // 以类广义表的形式输出二叉树T到gl_str printf("T = %s\n", gl_str); // 显示 pre = NULL; Status r = InOrderThreading(Thrt, T); // 算法6.6,6.7,中序线索化 printf("InOrderThreading(Thrt, T) : %s\n", (r) ? "OK" : "ERROR"); initVisitStr(); // 将visitStr清为空串 InOrderTraverse_Thr(Thrt, v

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值