c语言递归算法实现二叉树创建
时间: 2023-10-04 09:11:09 浏览: 81
C语言递归实现二叉树的建立.pdf
#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;
}
阅读全文