这个代码是使用占位符的方式创建二叉树
#include "stdio.h"
#include "stdlib.h"
typedef struct node {
char data;
struct node *lchild;
struct node *rchild;
} Node;
Node *create_node(char value) {
Node *node = (Node *) malloc(sizeof(Node));
if (node == NULL) {
exit(-1);
}
node->data = value;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
//递归创建二叉树
Node *create_tree(char *preOrder, int *index) {
char current = preOrder[*index];
if (current == '#' || current == '\0') {
*index = *index + 1;
return NULL;
}
//创建当前节点
Node *root = create_node(current);
*index = *index + 1;
root->lchild = create_tree(preOrder, index);
root->rchild = create_tree(preOrder, index);
return root;
}
void preOrderPrint(Node *node) {
if (node == NULL) {
return;
}
printf("%c ", node->data);
preOrderPrint(node->lchild);
preOrderPrint(node->rchild);
}
int main() {
char preOrder[] = "AEB#C###D##";
int index = 0;
Node *root = create_tree(preOrder, &index);
preOrderPrint(root);
return 0;
}
运行效果