Home>

I'm learning C language.
As the title suggests, I want to implement a function that displays the data inserted in the binary tree in ascending order, but I'm worried about how to do it.
I want to make it work normally, mainly by making changes to the void tree_print (tree_node_t * n) in the function file.
The program is as follows.

main file (tree9test.c)

include
include "tree.h"

int main (void)
{
tree_node_t * root = NULL;

for (;;) {
int data;
fprintf (stderr, "input =");
if (scanf ("% d",&data) == EOF) {break;}
root = tree_insert_uniq (root, data);
printf ("[");
tree_print (root);
printf ("] \ n");
}

tree_delete (root);
return 0;
}

h file (tree.h)

typedef struct tree_node_s {
struct tree_node_s * left;
struct tree_node_s * right;
int data;
} tree_node_t;

void tree_print (tree_node_t * root);
tree_node_t * tree_insert (tree_node_t * root, int v);
tree_node_t * tree_insert_uniq (tree_node_t * root, int v);
tree_node_t * tree_find (tree_node_t * root, int v);
void tree_delete (tree_node_t * root);

Function file (tree.c)

include
include
include
include "tree.h"

static tree_node_t * create_node (int val);

static tree_node_t * create_node (int val)
/ * Creates a new node with the value val and returns a pointer to that node * /
{
tree_node_t * new_node;
new_node = (tree_node_t *) malloc (sizeof (tree_node_t));
if (new_node == NULL) {
fprintf (stderr, "Failed to allocate node \ n");
exit (1);
}
new_node->data = val;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}

tree_node_t * tree_insert_uniq (tree_node_t * n, int val)
/ * Insert val (node) into a binary tree rooted at n * /
{
/ * Do not insert if there is a node with the same value as val * /

if (n == NULL) {
n = create_node (val);
}
else if (valdata) {
n->left = tree_insert_uniq (n->left, val);
}
else if (val>n->data) {
n->right = tree_insert_uniq (n->right, val);
}
else {;}

return n;
}

void tree_print (tree_node_t * n)
/ * Display the contents of the binary tree * /
{
if (n! = NULL) {
/ * I want to display in ascending order of values ​​* /

printf ("% d", n->data);
tree_print (n->left);
tree_print (n->right);
}
}

tree_node_t * tree_find (tree_node_t * n, int val)
Find a node with a value of val in a binary tree rooted at/* * n
Returns a pointer to that node if found, NULL otherwise * /
{
}

void tree_delete (tree_node_t * n)
/ * Release binary tree data * /
{
if (n! = NULL) {
tree_delete (n->left);
tree_delete (n->right);
free (n);
}
}

c
  • Answer # 1

    First, see the description of how to scan a tree structure on Wikipedia.
    In the current source, it is in the "going order" here, but
    If you want to scan in the order sorted by the binary search tree, you need to set it to "passing order".

  • Answer # 2

    printf ("% d", n->data);
    tree_print (n->left);
    tree_print (n->right);

    To

    tree_print (n->left);
    printf ("% d", n->data);
    tree_print (n->right);

    Just to