2009-07-19
对树形索引使用深度遍历的一个例子
标签:Java, 源代码, 算法对于树结构(典型的为二叉树),通常可以使用深度优先遍历和广度优先遍历两种方法来进行树节点的浏览,这些都是最基本的算法。以下就提供一个对于树形索引使用深度优先遍历的代码示例,由于代码中涉及到对于别的方法的调用,因此仅供参考,感兴趣的人理解算法思想即可。
- package com.databese.index.bplustree;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import com.databese.index.util.Const;
- import com.databese.index.util.Function;
- /**
- *
- * 对整个索引进行深度优先遍历,并生成对应XML文件
- *
- */
- public class DFSRetrieval {
- StringBuffer indexContent = new StringBuffer();
- /**
- * 构造函数
- * @param indexFilePath
- */
- public DFSRetrieval(String indexFilePath)
- {
- this.indexRetrieval(indexFilePath);
- this.write2XML();
- System.out.println("索引转换成XML文件成功!");
- }
- /**
- * 深度优先遍历
- * @param indexFilePath
- */
- public void indexRetrieval(String indexFilePath)
- {
- String indexName = Function.getIndexName(indexFilePath);
- BTree btree = BTree.openIndex(indexName);
- this.indexContent.append("<root>");
- this.nodeRetrieval(btree.index_head.root);
- this.indexContent.append("</root>");
- }
- /**
- * 将索引内容写到外部xml文件中
- *
- */
- public void write2XML()
- {
- try{
- BufferedWriter out = new BufferedWriter(new FileWriter(new File(Const.XML_PATH)));
- out.write(this.indexContent.toString());
- out.close();
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- public void nodeRetrieval(Node node)
- {
- //如果是叶子节点,就将所有的叶子节点关键字输出来
- if (node instanceof LeafNode) {
- for(int i=0; i<node.used_keys; i++)
- {
- this.indexContent.append("<key>")
- .append(node.keys[i])
- .append("</key>");
- }
- return ;
- }
- if(node instanceof InnerNode) {
- InnerNode innerNode = (InnerNode) node;
- for(int i=0; i<innerNode.used_keys; i++)
- {
- //读取孩子节点信息
- Node childNode = innerNode.getChildNode(i);
- this.indexContent.append("<point>");
- this.nodeRetrieval(childNode);
- this.indexContent.append("</point>");
- //读取关键字信息
- this.indexContent.append("<key>")
- .append(innerNode.keys[i])
- .append("</key>");
- }
- //根据节点中最后一个指针去获取孩子信息
- Node childNode = innerNode.getChildNode(innerNode.used_keys);
- this.indexContent.append("<point>");
- this.nodeRetrieval(childNode);
- this.indexContent.append("</point>");
- }
- return;
- }
- public static void main(String[] args) {
- DFSRetrieval dfsRetrieval = new DFSRetrieval("./index/all200000.index");
- }
- }
本文可以自由转载,转载时请保留全文并注明出处:
转载自仲子说 [ http://www.wangzhongyuan.com/ ]
原文链接:http://www.wangzhongyuan.com/archives/720.html