C语言写出非递归的方法创建二叉树,并输入输出数据
时间: 2024-06-01 10:09:35 浏览: 10
#include<stdio.h>
#include<stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 创建二叉树
struct TreeNode* createTree() {
struct TreeNode *root = NULL;
struct TreeNode *node = NULL;
int val;
printf("请输入根节点的值:");
scanf("%d", &val);
if (val == -1) {
return NULL;
} else {
root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = val;
root->left = NULL;
root->right = NULL;
}
while (1) {
printf("请输入左子节点的值:");
scanf("%d", &val);
if (val == -1) {
break;
} else {
node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
root->left = node;
}
printf("请输入右子节点的值:");
scanf("%d", &val);
if (val == -1) {
break;
} else {
node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
root->right = node;
}
}
return root;
}
// 前序遍历二叉树
void preOrder(struct TreeNode *root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历二叉树
void inOrder(struct TreeNode *root) {
if (root == NULL) {
return;
}
inOrder(root->left);
printf("%d ", root->val);
inOrder(root->right);
}
// 后序遍历二叉树
void postOrder(struct TreeNode *root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->val);
}
int main() {
struct TreeNode *root = createTree();
printf("前序遍历结果为:");
preOrder(root);
printf("\n中序遍历结果为:");
inOrder(root);
printf("\n后序遍历结果为:");
postOrder(root);
printf("\n");
return 0;
}
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)