Я хочу написать программу, которая может построить дерево бинарного поиска и показать
«Предзаказ», «Задание» и «Поступорядочение».
Первый ввод - это количество входных рядов,Начиная со второй строки, каждая строка представляет собой последовательный вход для построения бинарного дерева поиска.
Ввод:
3
9,5,6,7,1,8,3
22,86,-5,8,66,9
45,3,5,3,8,6,-8,-9
Вывод:
Preorder: 9 5 1 3 6 7 8
Inorder: 1 3 5 6 7 8 9
Postorder: 3 1 8 7 6 5 9
Preorder: 22 -5 8 9 86 66
Inorder: -5 8 9 22 66 86
Postorder: 9 8 -5 66 86 22
Preorder: 45 3 3 -8 -9 5 8 6
Inorder: -9 -8 3 3 5 6 8 45
Postorder: -9 -8 3 6 8 5 3 45
Вот мой кодобнаружить букву (,)
int limit,i;
char tree_input[1000];
char *pch;
scanf("%d",&limit);
printf("%d",limit);
for(i=0; i<limit; i++){
scanf("%s",tree_input);
pch = strtok (tree_input,",");
while (pch != NULL){
printf ("%s\n",pch);
pch = strtok (NULL, ",");
}
}
Моя идея состоит в том, чтобы использовать 'pch', чтобы быть деревом
И тогда я понятия не имею с следующим шагом. Это весь мой коддо сих пор.
Вот мой код
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int data)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(data);
/* Otherwise, recur down the tree */
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
/* return the (unchanged) node pointer */
return node;
}
void preorder(struct node* root)
{
if(root == NULL)
return;
printf("%d", root->data);
preorder(root->left);
preorder(root->right);
}
void inorder(struct node* root)
{
if(root == NULL)
return;
inorder(root->left);
printf("%d", root->data);
inorder(root->right);
}
void postorder(struct node* root)
{
if(root == NULL)
return;
postorder(root->left);
postorder(root->right);
printf("%d", root->data);
}
//void change(char a) //change char to int
//{
//
// for (char ch = '0'; ch <= '9'; ++ch) {
// printf("%d\t", ch - '0');
// }
//}
int main()
{
int limit,i;
char tree_input[1000];
char *pch;
scanf("%d",&limit);
printf("%d",limit);
for(i=0; i<limit; i++)
{
scanf("%s",tree_input);
pch = strtok (tree_input,",");
// struct node *root = NULL;
// root = insert(root, 50);
// insert(root, 30);
// insert(root, 20);
// insert(root, 40);
// insert(root, 70);
// insert(root, 60);
// insert(root, 80);
struct node *root = NULL;
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, ",");
printf("%d\n")
// if (root == NULL)
// {
// root = insert(root, pch);
// }
}
}
return 0;
}