递归算法实现二叉树的创建c语言
时间: 2023-10-04 17:14:35 浏览: 27
#include<stdio.h>
#include<stdlib.h>
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode *createTree(){
int val;
printf("请输入节点的值(输入-1表示结束):");
scanf("%d", &val);
if(val == -1){
return NULL;
}
struct TreeNode *node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = createTree();
node->right = createTree();
return node;
}
int main(){
struct TreeNode *root = createTree();
return 0;
}
相关问题
c语言递归算法实现二叉树创建
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
}TreeNode;
//递归创建二叉树
TreeNode* createTree(){
int val;
scanf("%d",&val);
if(val == -1) return NULL; //如果输入-1,说明该节点为空,返回NULL
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = createTree(); //递归创建左子树
node->right = createTree(); //递归创建右子树
return node;
}
//前序遍历二叉树
void preOrder(TreeNode *root){
if(root == NULL) return;
printf("%d ",root->val);
preOrder(root->left);
preOrder(root->right);
}
int main(){
TreeNode *root = createTree();
printf("前序遍历结果:");
preOrder(root);
return 0;
}
c语言用递归算法实现二叉树的代码
好的,以下是一个完整的 C 语言代码实现二叉树的中序遍历:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node *left;
struct node *right;
};
// 创建一个新节点
struct node* new_node(int val) {
struct node* node = (struct node*)malloc(sizeof(struct node));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 递归实现中序遍历
void inorder(struct node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
}
int main() {
// 创建一个二叉树
struct node* root = new_node(1);
root->left = new_node(2);
root->right = new_node(3);
root->left->left = new_node(4);
root->left->right = new_node(5);
// 中序遍历二叉树
printf("Inorder traversal of binary tree: ");
inorder(root);
return 0;
}
```
在以上代码中,`struct node` 表示二叉树的结构体,`new_node` 函数用于创建一个新的二叉树节点,`inorder` 函数是递归实现的中序遍历函数,`main` 函数是程序的入口函数,用于创建一棵二叉树并进行中序遍历。程序输出结果为:`Inorder traversal of binary tree: 4 2 5 1 3`,表示中序遍历的结果。
阅读全文