多叉树的创建和遍历(为Trie树做准备)

trie树实际上是一种多叉树的应用,Trie树是用来解决,搜索引擎中,输入前缀可以给出提示词的非常好的解决方案

在实现trie书算法以前,我们先回顾温习下,多叉树的实现和遍历(对于我们trie树的实现和便利帮助很大),这里就不说普通二叉树,因为原理一样,但相对简单

下面是算法实现,这个算法参考了<数据结构与算法分析>这本书中的描述和定义,用了一个很节省空间的结构定义

并没有在父节点中存储所有的子节点,而是存储了节点的链表,一般叫做二叉链表法,这样算法看起来非常像二叉树了

#include<stdio.h>
#include<stdlib.h>
#define maxsize 100
typedef struct node
{
 char *data;
 struct node *first_child,*next_sibling;//fc是第一个孩子,nb是fc的临节点
} tree;

/**
 a
 / \ \
 b c d
 /\ \
e f g
创建出来的树结构如上
 */

tree *insertTree(char *ch, tree *parent, tree *pre_sibling) {
 tree *child = (tree *)malloc(sizeof(tree));
 child->data = ch;

if (parent != NULL) parent->first_child = child;
 if (pre_sibling != NULL) pre_sibling->next_sibling = child;

child->first_child = NULL;
 child->next_sibling = NULL;

return child;
}

/**二叉链表创建树*/
tree *create() {
 //创建root节点
 tree *root = (tree *)malloc(sizeof(tree));
 root->data = "A";
 root->first_child = NULL;
 root->next_sibling = NULL;

/**
 * 创建多个子节点
 **/
 tree *b = insertTree("B", root, NULL);

tree *c = insertTree("C", NULL, b);
 tree *g = insertTree("G", c, NULL);
 //tree *h = insertTree("H", g, NULL);
 tree *d = insertTree("D", NULL, c);
 tree *e = insertTree("E", b, NULL);
 tree *f = insertTree("F", NULL, e);

return root;
}

void preOrder(tree *root) {
 printf("%c ",*root->data);
 if (root->first_child != NULL) {
 preOrder(root->first_child);
 }
 if (root->next_sibling != NULL) {
 preOrder(root->next_sibling);
 }
}

void postOrder(tree *root) {
 if (root->first_child != NULL) {
 postOrder(root->first_child);
 }
 printf("%c ",*root->data);
 if (root->next_sibling != NULL) {
 postOrder(root->next_sibling);
 }
}

int main()
{
 tree *root = create();
 printf("先序遍历:");
 preOrder(root);
 printf("后序遍历:");
 postOrder(root);
}

最终结果

先序遍历:A B E F C G D 后序遍历:E F B G C D A [Finished in 0.2s]

最后说一下数学之美中的一道题目,是按照层级遍历二叉树(当然可以推广到多叉树),这个以后再说吧,其实我一直在想如果数学之美中,这道题目不是限定的那么死,我们完全可以在数据结构上做文章,让这个问题变得很简单,就是在节点存储上同一层节点的链表,也算是借鉴了上面的一个结构描述

    原文作者:Trie树
    原文地址: https://blog.csdn.net/cfang2005/article/details/42496997
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞