实现三叉树的C ++程序
三叉树是一种树数据结构,其中每个节点最多具有三个子节点,通常表示为“左”,“中”和“右”。在此树中,具有子节点的节点是父节点,子节点可能包含对其父节点的引用。这是实现三叉树和遍历该树的C++程序。
算法
Begin
Declare function insert(struct nod** root, char *w)
if (!(*root)) then
*root = newnod(*w);
if ((*w) < (*root)->d) then
insert(&( (*root)->l ), w);
else if ((*w) > (*root)->d) then
insert(&( (*root)->r ), w);
else if (*(w+1))
insert(&( (*root)->eq ), w+1);
else
(*root)->EndOfString = 1;
End.对于遍历树:
Begin
Declare function traverseTTtil(struct nod* root, char* buffer,
int depth)
if (root) then
traverseTTtil(root->l, buffer, depth)
buffer[depth] = root->d
if (root->EndOfString) then
buffer[depth+1] = '\0'
print the value of buffer.
traverseTTtil(root->eq, buffer, depth + 1);
traverseTTtil(root->r, buffer, depth);
End.示例
#include<stdlib.h>
#include<iostream>
using namespace std;
struct nod {
char d;
unsigned End.
fString: 1;
struct nod *l, *eq, *r;
}*t = NULL;
struct nod* newnod(char d) {
t = new nod;
t->d = d;
t->End.
fString = 0;
t->l = t->eq = t->r = NULL;
return t;
}
void insert(struct nod** root, char *w) {
if (!(*root))
*root = newnod(*w);
if ((*w) < (*root)->d)
insert(&( (*root)->l ), w);
else if ((*w) > (*root)->d)
insert(&( (*root)->r ), w);
else {
if (*(w+1))
insert(&( (*root)->eq ), w+1);
else
(*root)->End.
fString = 1;
}
}
void traverseTTtil(struct nod* root, char* buffer, int depth) {
if (root) {
traverseTTtil(root->l, buffer, depth);
buffer[depth] = root->d;
if (root->End. String) {
buffer[depth+1] = '\0';
cout<<buffer<<endl;
}
traverseTTtil(root->eq, buffer, depth + 1);
traverseTTtil(root->r, buffer, depth);
}
}
void traverseTT(struct nod* root) {
char buffer[50];
traverseTTtil(root, buffer, 0);
}
int main() {
struct nod *root = NULL;
insert(&root, "mat");
insert(&root, "bat");
insert(&root, "hat");
insert(&root, "rat");
cout<<"Following is traversal of ternary tree\n";
traverseTT(root);
}输出结果
Following is traversal of ternary tree bat hat mat rat
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短