C语言创建树
所需要的文件
创建树一般是采用层次遍历创建的方法
1.先定义树中有什么,有值,有左右孩子指针,这个指针指向左右孩子,本质就是指向下一个节点
2.创建数组,只不过指针类型,每个指针都要指向一个新创建的结点
3.层次遍历树,用一个计数的j,层次遍历
C语言一般采用层次遍历建树
main.cpp
#include "tree.h"
#define N 10
void build_tree() {
pTNode tree_root = NULL;
char c[N+1] = "ABCDEFGHIJ";
//相当于创建了一个指针数组
pTNode p[N+1];
int i;
int j = 0;
for (i=0; i<N; i++) {
//创建一个节点,只不过这个结点只能是pTNode类型的指针来存
p[i] = (pTNode)calloc(1,sizeof(TNode));
p[i]->c = c[i];
// printf("/n---");
// printf("%c", p[i]->c);
}
for(i=0;i<N;i++){
if (NULL == tree_root) {
tree_root = p[i];
j = 0;
}
//层次遍历创建树
else {
if (NULL == p[j]->pleft) {
p[j]->pleft = p[i];
}
else if (NULL == p[j]->pright) {
p[j]->pright = p[i];
j++;
}
}
}
printf("\n--------------------\n");
pre_order(tree_root);
}
int main() {
build_tree();
}
tree.h
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char c;
struct node* pleft;
struct node* pright;
}TNode,*pTNode;
void pre_order(pTNode tree);
tree.cpp
#include "tree.h"
void pre_order(pTNode tree) {
if (tree) {
printf("%c",tree->c);
pre_order(tree->pleft);
pre_order(tree->pright);
}
}
标签:pre,创建,tree,C语言,printf,order,pTNode
From: https://www.cnblogs.com/hellojianzuo/p/16898424.html