普通树
普通树的存储有
双亲存储表示法
typedef struct
{
int data;
int parent;
}PTree[max_size];//P表示parent
孩子链表存储表示法
孩子链表和双亲存储表示法
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//采用孩子和双亲节点法来存储树,这里是任意的树。
#define max_Node 10
typedef struct childNode {//双亲节点的孩子节点
char data;
childNode* nextChild;
};
typedef struct parentNode {//双亲节点
char data;
childNode*firstChild;//指向第一个孩子
};
typedef struct Tree{
parentNode node[max_Node];
char r;//根节点
int n;//节点个数
}*TreePoint;
孩子兄弟链表存储
二叉树的链式存储
二叉树的初始化和输出都可采用,先序遍历,中序遍历,后序遍历,采用递归的算法。
先序为例
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//二叉树的存储,初始化,输出
char first[] = { 'A','B','#','#','C','D','#','#','E','F','#','#','G','#','#' };
int index = 0;
typedef struct BinTree {
BinTree*lchild;
BinTree*rchild;
char data;
}*BinTreePoint;
char getChar() {
if (first[index] != ' ') {
return first[index++];
}
return '&';//结尾标志
}
//先序遍历输入二叉树
void createBinTree(BinTreePoint &binTreePoint) {
char ch=getChar();
if (ch == '#') {
binTreePoint = NULL;
}
if(ch != '#') {
printf_s("单个字符为%c
", ch);
binTreePoint = (BinTreePoint)malloc(sizeof(BinTree));
if (binTreePoint == NULL) return ;
binTreePoint->data = ch;
createBinTree(binTreePoint->lchild);
createBinTree(binTreePoint->rchild);
}
}
//先序遍历输出二叉树
void printBinTree(BinTreePoint&binTreePoint) {
if (binTreePoint == NULL) {
return;
}
printf_s("%c", binTreePoint->data);
printBinTree(binTreePoint->lchild);
printBinTree(binTreePoint->rchild);
}
int main() {
BinTreePoint binTreePoint;
createBinTree(binTreePoint);
printf_s("%s
", "-----------------");
printBinTree(binTreePoint);
system("pause");
}