手动输入节点的一般二叉树c语言
时间: 2023-10-03 20:06:59 浏览: 45
好的,下面是一个简单的 C 语言程序,可以手动输入节点值,创建一般的二叉树:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
struct TreeNode* createTree() {
struct TreeNode* root = NULL;
int val;
printf("Enter root node value (-1 for no node): ");
scanf("%d", &val);
if (val == -1) {
return NULL;
}
root = createNode(val);
printf("Enter left child of %d:\n", val);
root->left = createTree();
printf("Enter right child of %d:\n", val);
root->right = createTree();
return root;
}
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
int main() {
struct TreeNode* root = createTree();
printf("Inorder traversal of the binary tree: ");
inorderTraversal(root);
return 0;
}
```
这个程序中,我们使用了递归的方式,通过输入每个节点的值,创建一颗二叉树。程序运行后,会要求你输入根节点的值,然后分别输入左子树和右子树的值,直到输入 -1 表示没有子节点为止。最后,程序会输出这个二叉树的中序遍历结果。