c语言递归实现二叉排序树
时间: 2023-10-21 09:36:47 浏览: 87
二叉排序树的C语言实现
5星 · 资源好评率100%
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *left;
struct node *right;
} Node;
Node *createNode(int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
Node *insertNode(Node *root, int data) {
if (root == NULL) {
root = createNode(data);
} else if (data < root->data) {
root->left = insertNode(root->left, data);
} else {
root->right = insertNode(root->right, data);
}
return root;
}
void inorderTraversal(Node *root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
int main() {
Node *root = NULL;
root = insertNode(root, 5);
root = insertNode(root, 3);
root = insertNode(root, 7);
root = insertNode(root, 1);
root = insertNode(root, 9);
printf("Inorder Traversal: ");
inorderTraversal(root);
return 0;
}
阅读全文