C 二叉樹實現詞頻分析功能

2022-09-29 21:54:27 字數 2791 閱讀 3545

通過二叉樹存單詞,並且對總共的單詞數量進行計數,二叉樹自適應的將出現頻率高的單詞往上移動以減少二叉樹的搜尋時間。

**如下

/***********************gensplay.h***********************/

#ifndef _gensplay_h_

#define _gensplay_h_

#include

using namespace std;

//樹節點

template

class splayingnode

splayingnode(const t &el, splayingnode *l = 0,

splayingnode *r = 0, splayingnode *p = 0)

:info(el), left(l), right(r), parent(p)

};//二叉樹

template

class splaytree

//虛函式

public:

splaytree()

void inorder()

t *search(const t &);

void insert(const t &);

};template

void splaytree::continuerotation(splayingnode *gr, splayingnode *par,

splayingnode *ch, splayingnode *desc)

else

root = ch;

if(desc != 0)

desc->parent = par;

par->parent = ch;

ch->parent = gr;

}template

void splaytree::rotater(splayingnode *p)

template

void splaytree::rotatel(splayingnode *p)

template

void splaytree::semisplay(splayingnode *p)

else if(p->parent->left == p)

else

}else

else

}if(root == null)

root = p;

}}template

t *splaytree::search(const t &el)

else if(el < p->info)

p = p->left;

else

p = p->right;

} return 0;

}template

void splaytree::insert(const t &el)

if((newnode = new splayingnode(el, 0, 0, prev)) == 0)

ifwww.cppcns.com(root == 0)

root = newnode;

else if(el < prev->info)

prev->left = newnode;

else

prev->right = newnode;

}template

void splaytree::inorder(splayingnode *p)

}#endif // _gensplay_h_

/***********************splay.cpp***********************/

#include

#include

#include

#include

#include //exit(0)

#include "gensplay.h"

using namespace std;

//用作計數物件的類

class word

void run(ifstream &, char *);

};void wordsplay::visit(splayingnode *p)

void wordsplay::run(ifstream &fin, char *filename)

if(fin.eof())

break;

for(i = 0; !fin.eof() && isalpha(ch); i++)

s[i] = '\0';

if(!(rec.word = new char[strlen(s) + 1]))

strcpy(rec.word, s);

word *p = search(rec);

if(p == 0)

insert(rec);

else

p->freq++;

} inorder();

cout << "\n\nfile " << filename

<< " contains " << wordcnt << " words among which "

<< differentwords << " are different.\n";

}int main()

splaytree.run(fin, filename);

fin.close();

return 0;

}有空回來補充相應的其他功能:

將對應的單詞和檔案寫到檔案裡面去,先序遍歷

優化效能

本文標題: c++二叉樹實現詞頻分析功能

本文位址:

C 實現二叉樹

其中的 linkstack.h 和 linkqueue 分別在 以下兩篇博文裡 linkstack linkqueue include include linkstack.h include linkqueue.h using namespace std 定義節點 templatestruct no...

二叉樹C 實現

最近整理原來的一些 腦子有點不好使,還是記下來吧。binary tree.h,遍歷包含了遞迴和非遞迴兩種,層次遍歷 ifndef binary tree h define binary tree h templatestruct binode templateclass bitree endif b...

C 實現二叉樹

實現 pragma once include include include using namespace std templatestruct bintreenode templateclass binarytree binarytree char str 根據先序字串行建立二叉樹 binary...