C语言 C语言树数据结构教程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3305321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tutorial for Tree Data Structure in C
提问by The Stig
Could someone direct me to some tutorial on Tree Data Structures using C. I tried googling but most implementations are for C++ or Java.If someone can point me to some online tutorials that are in C it would be great.
有人可以指导我使用 C 学习一些关于树数据结构的教程。我尝试过谷歌搜索,但大多数实现都是针对 C++ 或 Java 的。如果有人可以指点我一些 C 语言的在线教程,那就太好了。
Thanks..
谢谢..
回答by eruciform
Generic tree-traversal methods: http://en.wikipedia.org/wiki/Tree_traversal(see right sidebar for a huge list of algorithms to choose from).
通用树遍历方法:http: //en.wikipedia.org/wiki/Tree_traversal(请参阅右侧边栏以获取大量可供选择的算法列表)。
Some tutorials:
一些教程:
回答by Jerry Coffin
Here's a bit of tutorial code from a couple of decades ago. In fact, it's been lying around so long, I don't remember where it came from or who wrote it (could have been me, but I'm really not sure). Theoretically it's a bit non-portable, using strdup, which isn't part of the standard library, though most compilers have/supply it.
这是几十年前的一些教程代码。事实上,它已经存在了很长时间,我不记得它来自哪里或是谁写的(可能是我,但我真的不确定)。理论上它有点不可移植,使用strdup,它不是标准库的一部分,尽管大多数编译器都有/提供它。
/* Warning: untested code with no error checking included. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A tree node. Holds pointers to left and right sub-trees, and some data (a string).
*/
typedef struct node {
struct node *left;
struct node *right;
char *string;
} node;
node *root; /* pointers automatically initialized to NULL */
int insert(const char *string, node *root) {
/* Add a string to the tree. Keeps in order, ignores dupes.
*/
int num = strcmp(root->string, string);
node *temp;
for(;;) {
if ( 0 == num)
/* duplicate string - ignore it. */
return 1;
else if (-1 == num) {
/* create new node, insert as right sub-tree.
*/
if ( NULL == root -> right ) {
temp = malloc(sizeof(node));
temp -> left = NULL;
temp -> right = NULL;
temp -> string = strdup(string);
return 2;
}
else
root = root -> right;
}
else if ( NULL == root ->left ) {
/* create new node, insert as left sub-tree.
*/
temp = malloc(sizeof(node));
temp -> left = NULL;
temp -> right = NULL;
temp -> string = strdup(string);
return 2;
}
else
root = root -> left;
}
}
void print(node *root) {
/* in-order traversal -- first process left sub-tree.
*/
if ( root -> left != NULL )
print(root->left);
/* then process current node.
*/
fputs(root->string, stdout);
/* then process right sub-tree
*/
if ( root->right != NULL )
print(root->right);
}
int main() {
char line[100];
/* Let user enter some data. Enter an EOF (e.g., ctrl-D or F6) when done.
*/
while ( fgets(line, 100, stdin))
insert(line, root);
/* print out the data, in order
*/
print(root);
return 0;
}

