#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *left;
struct node *right;
} Node;
typedef struct tree {
Node *root;
} Tree;
void insert(Tree &tree, int value) {
Node *node = static_cast<Node *>(malloc(sizeof(Node)));
node->data = value;
node->left = NULL;
node->right = NULL;
if (tree.root == NULL) {
tree.root = node;
} else {
Node *temp = tree.root;
while (temp != NULL) {
if (value < temp->data) {
if (temp->left == NULL) {
temp->left = node;
return;
} else {
temp = temp->left;
}
} else {
if (temp->right == NULL) {
temp->right = node;
return;
} else {
temp = temp->right;
}
}
}
}
}
void display(Node *node) {
if (node != nullptr) {
display(node->left);
printf("%d\n", node->data);
display(node->right);
}
}
int main() {
int arr[7] = {6, 3, 8, 2, 5, 1, 7};
Tree tree;
tree.root = NULL;
for (int i = 0; i < 7; ++i) {
insert(tree, arr[i]);
}
display(tree.root);
}
评论 (0)