#include<stdio.h>
#include<stdlib.h>typedef struct node
{int data;struct node * left;struct node * right;
} Node;Node * createNode(int val);
Node * createTree();
void freeTree(Node * node);void preOrder(Node * node);// 先序创建二叉树
int main() {Node * root = createTree();preOrder(root);freeTree(root);return 0;
}Node * createNode(int val) {Node * node = (Node *)malloc(sizeof(Node));if (node == NULL){printf("内存申请异常");exit(-1);}node->data = val;node->left = NULL;node->right = NULL;return node;
}Node * createTree() {int val = 0;printf("请输入创建树的数据 0为NULL:");scanf("%d", &val);if (val == 0){return NULL;}Node * node = createNode(val);printf("请输入%d的左子节点:", val);node->left = createTree();printf("请输入%d的右子节点:", val);node->right = createTree();return node;
}void preOrder(Node * node) {if (node == NULL){return;}printf("%d ", node->data);preOrder(node->left);preOrder(node->right);
}void freeTree(Node * root) {if (root == NULL){return;}freeTree(root->left);freeTree(root->right);free(root);
}
这棵树的结构为
运行效果