用c++写一个二叉树的建立
时间: 2024-05-20 20:16:51 浏览: 45
c++创建二叉树
#include <stdio.h>
#include <stdlib.h>
//定义二叉树结构体
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
//创建二叉树
TreeNode* createTree() {
int data;
scanf("%d", &data);
if (data == 0) { //输入0表示该节点为空
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); //创建根节点
root->data = data;
root->left = createTree(); //递归创建左子树
root->right = createTree(); //递归创建右子树
return root;
}
//先序遍历
void preorder(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
//中序遍历
void inorder(TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
//后序遍历
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
int main() {
TreeNode* root = createTree();
printf("先序遍历:");
preorder(root);
printf("\n");
printf("中序遍历:");
inorder(root);
printf("\n");
printf("后序遍历:");
postorder(root);
printf("\n");
return 0;
}
阅读全文