BST insertion function causes weird output (C) - c

I am trying to write a program that takes a newline separated list of strings from a file and one by one inserts them into a BST.
The way I have it now results in the tree having all of the node's values be the value of the last string added to the tree.
For example, if the list being inserted is: b a c e d z, an inorder traversal will print the tree as: z z z z z z.
I've traced through this code a large number of times over and can not see what's causing this, i've hit a complete mental block.
Here is the code:
insert.c:
#include "node.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void insert_node(Node* root, char *nextString) {
Node* freshNode;
freshNode = newNode();
freshNode->Word = nextString;
printf("Root->Word = %s\n",root->Word);
printf("nextString = %s\n",freshNode->Word);
int newLessThanRoot = 0;
if (strcmp(root->Word,freshNode->Word) > 0) {
newLessThanRoot = 1;
}
if (newLessThanRoot) {
if (root->Left == NULL) {
root->Left = freshNode;
}
else {
insert_node(root->Left, freshNode->Word);
}
}
if (!newLessThanRoot) {
if (root->Right == NULL) {
root->Right = freshNode;
}
else {
insert_node(root->Right, freshNode->Word);
}
}
}
void inorder(Node *temp) {
if (temp != NULL) {
inorder(temp->Left);
printf("%s ",temp->Word);
inorder(temp->Right);
}
}
relevant parts of main.c:
char inputString[15];
char *inputStringPtr = &inputString[0];
Node* root;
root = newNode();
fscanf(infile,"%s",inputStringPtr);
root->Word = inputString;
printf("Root's word: %s\n",root->Word);
while (fscanf(infile,"%s",inputStringPtr) == 1) {
insert_node(root,inputStringPtr);
printf("%s\n",inputString);
}
int numberOfStrings = num_of_strings(root);
int heightOfBST = height_of_tree(root);
int numberOfLeaves = num_of_leaves(root);
inorder(root);

Related

Using recursive DFS to find node in binary tree

I have to use DFS to search a binary tree to find a node. (tok is the string I'm searching for). If it finds it, it has to return the number of nodes it traversed to find it. If it doesn't then it has to return -1.
I have tried many recursive solutions but honestly, I'm stumped. I may not be returning values correctly.
Test case:
Lets say i have a tree with the root called "John"."John" as a left child "Shayne" and a right child "Eric". Additionally, "Shayne" has a left child "Max". The output would be correct for John,Shayne and Max. But the output of Eric should be 4, since i traverse john and then shayne and then max and then Eric (considering im going left first and then right), but for Eric, im getting the output of 3
Edited with exact test case.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char* name;
char* tea;
struct node* left;
struct node* right;
};
typedef struct node Node;
int depth(struct node* root);
int dfs(struct node* root, char* tok);
int main() {
Node* John = (Node*)malloc(sizeof(Node));
John->left = NULL;
John->right = NULL;
John->name = "John";
Node* Shayne = (Node*)malloc(sizeof(Node));
Shayne->left = NULL;
Shayne->right = NULL;
Shayne->name = "Shayne";
Node* Eric = (Node*)malloc(sizeof(Node));
Eric->left = NULL;
Eric->right = NULL;
Eric->name = "Eric";
Node* Max = (Node*)malloc(sizeof(Node));
Max->left = NULL;
Max->right = NULL;
Max->name = "Max";
John->left = Shayne;
Shayne->left = Max;
John->right = Eric;
printf("%d",dfs(John,"Eric"));
}
int depth(struct node* root) {
if (root == NULL) {
return 0;
}
int l = depth(root->left);
int r = depth(root->right);
int d = max(l, r) + 1;
return d;
}
int dfs(struct node* root, char* tok) {
if (root == NULL) {
return 0;
}
if (strcmp(root->name, tok) == 0) {
return 1;
}
else {
int l = dfs(root->left, tok);
if (l != -1) {
return 1 + l;
}
int r = dfs(root->right, tok);
if (r != -1) {
return 1+l+ r;
}
return -1;
}
}
You correctly add 1 to the return value when the value has been found in an immediate child to produce the number of nodes. But it also means that you will return 2 to your parent.
You have to change your test to
if (l != -1) { //found on left child
return 1 + l;
}
The only problem with your function is that when you are returning from the child node you are always checking the value of l with 1 for instance:
int l = dfs(root->left, tok);
if (l == 1) { //found on left child
return 1 + l;
}
which will work fine for the first 2 nodes but then the value of the return becomes 2,3,4,.... in that case it will skip the if and return -1 again, so to solving this problem a good approach will be to check if the return value is not -1, for example:
int l = dfs(root->left, string);
if (l != -1) {
return 1 + l;
}
int r = dfs(root->right, string);
if (r != -1) {
return 1 + r;
}
Hope this gives you the answer.

C singly linked list using Queue

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include "locker.h"
void QueueInit(Queue* p)
{
p->front = NULL;
p->rear = NULL;
}
int QIsEmpty(Queue* p)
{
if(p->front == NULL)
{
return 1;
}
return 0;
}
void Enqueue(Queue* p, int data)
{
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->next = NULL;
newNode->id = data;
if(QIsEmpty(p))
{
p->front = newNode;
p->rear = newNode;
} else {
p->rear->next = newNode;
p->rear = newNode;
}
}
void attachEnqueue(Queue* p, int user_id)
{
Node* temp = p->front;
temp->user_id = user_id;
p->front = temp;
printf("Locker %d Owned By %d\n", temp->id, temp->user_id);
temp->owned = 1;
temp = temp->next;
}
int Dequeue(Queue* p)
{
Node* temp = p->front;
uint16_t item;
if(QIsEmpty(p))
{
printf("No element exists!");
exit(0);
} else {
item = temp->id;
p->front = temp->next;
free(temp);
if(temp == NULL)
{
p->rear = NULL;
}
return (item);
}
}
void printList(Queue* p)
{
Node* v = p->front;
while(v != NULL){
printf("Locker: %d\n", v->id);
v = v->next;
}
}
int count (Queue p)
{
int c = 0 ;
Node* temp = p.front ;
while ( temp != NULL )
{
temp = temp->next;
c++ ;
}
return c ;
}
void SearchQueue(Queue* p, int val1)
{
Node* v = p->front;
int sw = 0;
while( v != NULL)
{
if(v->id == val1)
{
printf("Locker ID: %d\n", val1);
printf("Lock Status: locked\n");
if(v->owned == 0){
printf("unowned\n");
} else if(v->owned == 1)
{
printf("owned by %d\n", v->user_id);
}
sw = 1;
}
v = v->next;
}
if(!sw)
{
printf("locker %d does not exists\n", val1);
}
}
int main(int argc, char* argv[])
{
Queue queue;
QueueInit(&queue);
char input[50];
char command[20];
int val1;
uint16_t id = 1;
while(1)
{
scanf(" %49[^\n]s", input);
sscanf(input, "%s %d", &command, &val1);
if(strcmp(command, "CREATE") == 0)
{
printf("New Locker created: %d\n", id);
Enqueue(&queue, id);
id++;
} else if(strcmp(command, "DISPLAY") == 0)
{
SearchQueue(&queue, val1);
} else if(strcmp(command, "ATTACH") == 0)
{
attachEnqueue(&queue, val1);
} else if(strcmp(command, "DISPLAYALL") == 0)
{
printList(&queue);
}else if(strcmp(command, "DELETE") == 0)
{
printf("Deleted the locker, %d\n",Dequeue(&queue));
}else if(strcmp(command, "QUIT") == 0)
{
printf("Good Bye!\n");
exit(0);
}
continue;
}
return 0;
}
This is what I have so far and the contents for "locker.h" is:
#ifndef LOCKER_H
#define LOCKER_H
#include <stdint.h>
typedef struct locker_t {
uint16_t id;
uint16_t user_id;
uint8_t locked;
uint8_t owned;
int write_fd;
int read_fd;
struct locker_t* next;
}Node;
typedef struct queue_t {
Node* front;
Node* rear;
size_t size;
}Queue;
#endif
Everything works fine except for the attachEnqueue part.
The purpose is, when I create locker 1 and locker 2 and input ATTACH 20,
locker 1's owner should be 20 and again if I input ATTACH 30, locker 2`s owner should be 30.
However, when I create 2 lockers and firstly ATTACH 20 and then again input ATTACH 30, the locker 1's owner`s value only changes from 20 to 30, not assigning the 30 owner to locker 2.
I am 100% sure that the attachEnqueue function involves the wrong contents but I am really not sure how to modify it..
Also, I need to include a "LOCK" command to make the locker whether to be locked or unlocked, but the problem is, school wants me to do this by using signal SIGUSR. How should I use the signal function to lock or unlock the locker? Would pthread.mutex.lock and unlock work?
Any help or advice would be very thankful!
The comment is right. The last line of attachEnqueue is temp = temp->next;
Maybe you assume temp keeps that information in mind next time you call the function, but right now, absolutely not. This line is of no use, the next time, temp will be assigned to the front of the queue.
To go around that, you may create a flag in your struct as stated above, add a counter argument to your function to keep track of which element in your queue to attach, or make temp a static argument, so its state persists between calls.

Using getchar() to read text with no trailing newline

I'm working on a program with the goal of reading parentheses/brackets and figuring out if they are balanced on each side, but am running into trouble when reading the last line of text. This may be a little confusing, but I'll attach the input:
3 <-- The number of lines I'll scan
([]) <-- Problem
(([{}])))
([()[]()])()
My program works perfectly when faced with manual input; that is when I input each line myself and press enter. When I copy a block of text though, the program fails to print the final answer (yes or no) unless I press enter. This is my code :
#include <stdio.h>
#include <stdlib.h>
#ifndef status_h
#define status_h
enum status { SUCCESS, FAILURE };
typedef enum status Status;
enum boolean { TRUE, FALSE };
typedef enum boolean Boolean;
#endif
typedef void* NODE;
struct node {
char data;
struct node* next;
} *head;
typedef struct node Node;
void stack_init_default(Node* hStack);
int stack_empty(void);
char stack_top(Node* hStack);
NODE stack_pop(Node* hStack);
NODE stack_push(Node* hStack, char item);
void stack_destroy(void);
int main(int charc, char* argv[])
{
char x;
int num, error = 0, i;
Node* stack;
stack_init_default(stack);
scanf("%d ", &num);
for (i = 0; i < num; i++)
{
stack_destroy();
error = 0;
while ((x = getchar()) != '\n' )
{
if (x == ' ')
continue;
if ((x == '(')||(x == '[')||(x == '{'))
{
stack_push(stack, x);
}
else if ((x == ')')&&(stack_top(stack)=='('))
{
stack_pop(stack);
}
else if ((x == ']')&&(stack_top(stack)=='['))
{
stack_pop(stack);
}
else if ((x == '}')&&(stack_top(stack)=='{'))
{
stack_pop(stack);
}
else
{
error = 1;
}
}
putchar('\n');
if (stack_empty() == 0 || error == 1)
{
printf("No");
}
else
{
printf("Yes");
}
}
printf("\n");
return 0;
}
void stack_init_default(Node* hStack)
{
head = NULL;
}
NODE stack_push(Node* hStack, char item)
{
Node* tmp = (Node*)malloc(sizeof(Node));
if(tmp == NULL)
{
exit(0);
}
tmp->data = item;
tmp->next = head;
head = tmp;
return head;
}
NODE stack_pop(Node* hStack)
{
Node* tmp = head;
head = head->next;
free(tmp);
return head;
}
char stack_top(Node* hStack)
{
if (head == NULL)
{
return '\0';
}
return head->data;
}
int stack_empty(void)
{
return (head == NULL);
}
void stack_destroy(void)
{
Node* phStack = head;
while (head != NULL)
{
phStack = head->next;
free(head);
head = phStack;
}
free(phStack);
head = NULL;
}
My issue looks like this:
3
([])
(([{}])))
([()[]()])()
Yes
No
Yes
So my program outputs yes or no, but freezes on the last problem, waiting for me to press newline to finish the loop. I assume that the issue lies somewhere with the while loop, and that because the pasted text doesn't have a final newline the loop never ends, but I'm unsure how to fix this. Thanks for any help.

Binary Tree segmentation fault after implementing search function

i am trying to write a program that will do the following
-read a file from std in
-read each line, and add each line to a binary tree
*if name is already in binary tree,dont add the name to the tree again but update its count of repititions
-print out the binary tree
the file being read in looks something like
dylan
bob
dylan
randall
randall
so when i print out the binary tree i would like it to print out
bob 1
dylan 2
randall 2
i was able to successfully print out the names without worrying about repetitions. I have commented out the blocks of code that mess my program up which is anything interacting with my search function that i added after the fact to take care of repetitions. The code builds a binary tree with each "leave" being a structure of 4 parts,the name,thecount,and the pointers to left and right childs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char* name;
int count;
struct node* left;
struct node* right;
};
struct node* addNode(char* string);
void insert(struct node *root, char* stringgg);
void preorder(struct node *root);
int search(struct node* leaf,char* string2find);
int main()
{
char buffer[20];
struct node *root = NULL;
while( fgets(buffer, sizeof(buffer), stdin) != NULL )
{
if(root == NULL)
root = addNode(buffer);
else
insert(root,buffer);
}
preorder(root);
}
struct node* addNode(char* string)
{
struct node *temp = malloc(sizeof(struct node));
temp->name = malloc(strlen(string) + 1);
strcpy(temp->name,string);
temp->left = NULL;
temp->right = NULL;
return temp;
}
void insert(struct node *root, char* stringgg)
{
/* int flag = 5;
flag = search(root,stringgg);
if(flag == 1)
return; */
if(strcmp(stringgg,root->name) < 0)
{
if(root->left == NULL)
root->left = addNode(stringgg);
else
insert(root->left, stringgg);
}
else
{
if(root->right == NULL)
root->right = addNode(stringgg);
else
insert(root->right,stringgg);
}
}
/*int search(struct node* leaf,char* string2find)
{
if(strcmp(string2find,leaf->name) == 0)
{
leaf->count = leaf->count + 1;
return 1;
}
else if(strcmp(string2find,leaf->name) < 0)
{
return search(leaf->left,string2find);
}
else
{
return search(leaf->right,string2find);
}
return 0;
} */
void preorder(struct node *root)
{
if(root == NULL)
return;
printf("%s",root->name);
preorder(root->left);
preorder(root->right);
}
the above code prints out all the names even if there already in a tree. I was hoping that someone would be able to point out my search function errors so that it wont cause a segmentation fault when printing. Possible causes may be my inappropriate use of the return function in which i am trying to return to main if flag == 1 which means match was found so dont addnodes. but if flag does not equal 1 no match was found so go about adding nodes.
at main
while( fgets(buffer, sizeof(buffer), stdin) != NULL ){
char *p = strchr(buffer, '\n');
if(p) *p=0;//remove '\n'
at addNode
temp->count = 1;//initialize counter
return temp;
at insert
void insert(struct node *root, char* stringgg){
int cmp_stat = strcmp(stringgg,root->name);
if(cmp_stat == 0)
root->count++;
else if(cmp_stat < 0) {
if(root->left == NULL)
root->left = addNode(stringgg);
else
insert(root->left, stringgg);
} else {
if(root->right == NULL)
root->right = addNode(stringgg);
else
insert(root->right,stringgg);
}
}
at preorder
printf("%s %d\n",root->name, root->count);
The error is in searching for the very first item in the empty tree — you call
search(root, stringgg)
but root is NULL, so in search() you call
strcmp(string2find, leaf->name)
with leaf == NULL and the program crashes.
A cure: do not search BEFORE you update your tree, but rather search TO update it.
struct node* update(struct node* nd, const char* str)
{
int cmp;
// (sub)tree is empty? - create a new node with cnt==1
if(nd == NULL)
return CreateNode(str);
// test if the node found
cmp = strcmp(str, nd->name);
if(cmp == 0) // YES
nd->count ++; // update the counter
else if(cmp < 0) // NO - search in a subtree
nd->left = update(nd->left, str);
else
nd->right = update(nd->right, str);
return nd; // return the updated subtree
}
Then in main() you just update the tree and store it:
root = update(root, buffer);
Actually, the root value will change only once, on the first call, and all subsequent assignments will not change its value. However that makes the code much more readable.

Creating a binary search tree in C99

I've got a programming class assignment due tonight at 8 PM CDT that I'm having trouble with. We are to take a list of the following numbers via reading a file:
9
30
20
40
35
22
48
36
37
38
place them in an array (easy enough), and then read these into a binary search tree using C. The first number in the list is the number of elements in the tree. The rest are placed into the following struct:
typedef struct node_struct {
int data;
struct node_struct* left;
struct node_struct* right;
} Node;
I think I've got the first part down pat. Take the stuff in using fscanf (I didn't choose to use this method, I like fgets better), call an insertion function on each member of the array, then call a "createNode" function inside the insertion function.
Problem is, I'm only getting one member into the BST. Furthermore, the BST must satisfy the condition node->left->data <= node->data < node->right->data... in other words, the nodes must be in order in the tree.
Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// def BST node struct
typedef struct node_struct {
int data;
struct node_struct* left;
struct node_struct* right;
} Node;
// prototypes
Node* createNode(int data);
Node* bstInsert(Node* root, int data);
// helper function prototypes
void padding(char ch, int n);
void displayTree(Node* root, int depth);
int main(int argc, char **argv)
{
FILE *in = NULL;
int num_read, count=0, array_size = 0;
if(argc != 2){
printf("hw3 <input-file>\n");
return 1;
}
in = fopen(argv[1], "r");
if(in == NULL){
printf("File can not be opened.\n");
return 2;
}
// read in the first line to get the array size
fscanf(in, "%d", &array_size);
// declare the array
int array[array_size];
// read from the second line to get each element of the array
while(!feof(in)){
fscanf(in, "%d", &num_read);
array[count] = num_read;
count++;
}
fclose(in);
if (array_size != count) {
printf("data error. Make sure the first line specifies the correct number of elements.");
return 3;
}
Node *root1 = NULL, *root2 = NULL, *root3 = NULL;
int i;
// task1: construct a bst from the unsorted array
printf("=== task1: construct a bst from the unsorted array ===\n");
for (i = 0; i < array_size; i++) {
root1 = bstInsert(root1, array[i]);
}
displayTree(root1, 0);
return 0;
}
Node* bstInsert(Node* root, int data) {
if(root == NULL){
root = createNode(data);
if(root != NULL){
root= createNode(data);
}
else{
printf("%d not inserted, no memory available.\n", data);
}
}
Node* current, previous, right;
current = root;
previous = root->left;
next = root->right;
else{
if(previous->data <= current->data){
}
}
return root;
}
Node* createNode(int data) {
// TODO
Node* aRoot;
if(!data)
return NULL;
aRoot = malloc(sizeof(Node));
if(!aRoot){
printf("Unable to allocate memory for node.\n");
return NULL;
}
aRoot->data = data;
aRoot->left = NULL;
aRoot->right = NULL;
return aRoot;
}
/* helper functions to print a bst; You just need to call displayTree when visualizing a bst */
void padding(char ch, int n)
{
int i;
for (i = 0; i < n; i++)
printf("%c%c%c%c", ch, ch ,ch, ch);
}
void displayTree(Node* root, int depth){
if (root == NULL) {
padding (' ', depth);
printf("-\n");
}
else {
displayTree(root->right, depth+1);
padding(' ', depth);
printf ( "%d\n", root->data);
displayTree(root->left, depth+1);
}
}
main, createNode, displayTree, and padding are okay, I believe. It's bstInsert where I'm having trouble. I'm just not sure how to order things to create a valid tree.
EDIT:
I've edited bstInsert and injected some more logic. It should be printing out more leaves on the tree, but alas, it's only printing out the number "30". Here's the new function.
Node* bstInsert(Node* root, int data) {
if(root == NULL){
root = createNode(data);
if(root != NULL){
root= createNode(data);
}
else{
printf("%d not inserted, no memory available.\n", data);
}
}
else{
if(data < root->data){
bstInsert(root->left, data);
}
else if(data > root->data || data == root->data){
bstInsert(root->right, data);
}
}
return root;
}
You have to assign the newly created node pointer to the correct part of the tree. This code does that. The key change is using the return value from bstInsert() correctly. The other changes are cosmetic. Note that I checked the input array by printing it out; also, it is sensible to print out the BST as you build it.
Don't use feof() as a loop control condition. It is almost invariably wrong when used as a loop control, but at least you have to also check the input operation that follows. I've written a lot of programs in my time; I've hardly ever used feof() (I found two places in my own code with it; in both, it was correctly used to distinguish between EOF and an error after an input had failed.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// def BST node struct
typedef struct node_struct
{
int data;
struct node_struct* left;
struct node_struct* right;
} Node;
// prototypes
Node *createNode(int data);
Node *bstInsert(Node *root, int data);
// helper function prototypes
void padding(char ch, int n);
void displayTree(Node *root, int depth);
int main(int argc, char **argv)
{
FILE *in = NULL;
int num_read, count=0, array_size = 0;
if (argc != 2)
{
printf("hw3 <input-file>\n");
return 1;
}
in = fopen(argv[1], "r");
if (in == NULL)
{
printf("File can not be opened.\n");
return 2;
}
// read in the first line to get the array size
fscanf(in, "%d", &array_size);
// declare the array
int array[array_size];
// read from the second line to get each element of the array
while (count < array_size && fscanf(in, "%d", &num_read) == 1)
array[count++] = num_read;
fclose(in);
if (array_size != count)
{
printf("data error. Make sure the first line specifies the correct number of elements.");
return 3;
}
for (int i = 0; i < array_size; i++)
printf("%d: %d\n", i, array[i]);
Node *root1 = NULL;
// task1: construct a bst from the unsorted array
printf("=== task1: construct a bst from the unsorted array ===\n");
for (int i = 0; i < array_size; i++)
{
root1 = bstInsert(root1, array[i]);
displayTree(root1, 0);
}
displayTree(root1, 0);
return 0;
}
Node *bstInsert(Node *root, int data)
{
if (root == NULL)
{
root = createNode(data);
if (root == NULL)
printf("%d not inserted, no memory available.\n", data);
}
else if (data < root->data)
root->left = bstInsert(root->left, data);
else
root->right = bstInsert(root->right, data);
return root;
}
Node *createNode(int data)
{
Node *aRoot;
aRoot = malloc(sizeof(Node));
if (!aRoot)
{
printf("Unable to allocate memory for node.\n");
return NULL;
}
aRoot->data = data;
aRoot->left = NULL;
aRoot->right = NULL;
return aRoot;
}
/* helper functions to print a bst; You just need to call displayTree when visualizing a bst */
void padding(char ch, int n)
{
for (int i = 0; i < n; i++)
printf("%c%c%c%c", ch, ch, ch, ch);
}
void displayTree(Node *root, int depth)
{
if (root == NULL) {
padding (' ', depth);
printf("-\n");
}
else {
displayTree(root->right, depth+1);
padding(' ', depth);
printf ( "%d\n", root->data);
displayTree(root->left, depth+1);
}
}
Ok, think about what you want to do in the different tree configurations:
when the tree is empty -> create a root node
when the tree isn't empty -> how do the value to be inserted and the value of the root compare?
above -> insert in the right subtree
below -> insert in the left subtree
equal -> do nothing (this actually depends on how your assignment tells you to treat duplicates)
From this basic algorithm, you should be able to figure out all the corner cases.
A simplified solution (naive insertion with recursion, data input noise removed):
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
static int nums[] = { 6, 8, 4, 1, 3, 7, 14, 10, 13 }; // instead of the user input
typedef struct _node {
int value;
struct _node *left;
struct _node *right;
} node;
node *node_new(int v)
{
node *n = malloc(sizeof(*n));
assert(n);
n->value = v;
n->left = NULL;
n->right = NULL;
return n;
}
void insert(node **tree, node *leaf)
{
if (*tree == NULL) {
*tree = leaf;
} else if (leaf->value > (*tree)->value) {
insert(&((*tree)->right), leaf);
} else {
insert(&((*tree)->left), leaf);
}
}
void dump(node *tree, int level)
{
static const char *pad = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
if (tree != NULL) {
printf("%sSelf: %d\n", pad + 16 - level, tree->value);
if (tree->left) {
printf("%sLeft node:\n", pad + 16 - level);
dump(tree->left, level + 1);
}
if (tree->right) {
printf("%sRight node:\n", pad + 16 - level);
dump(tree->right, level + 1);
}
} else {
printf("%sEmpty\n", pad + 16 - level);
}
}
int main()
{
size_t n = sizeof(nums) / sizeof(*nums);
int i;
node *tree = NULL;
for (i = 0; i < n; i++) {
insert(&tree, node_new(nums[i]));
}
dump(tree, 0);
// give some work to the kernel
return 0;
}
You should consider doing this recursively. Remember that each node is a tree in itself:
#include <stdio.h>
#include <stdlib.h>
typedef struct tree_struct {
int value;
struct tree_struct* left;
struct tree_struct* right;
} Tree;
Tree* addToTree(int value, Tree* tree)
{
if (tree == NULL) {
tree = malloc(sizeof(Tree));
tree->value = value;
tree->left = NULL;
tree->right = NULL;
} else {
if (value < tree->value) {
tree->left = addToTree(value, tree->left);
} else {
tree->right = addToTree(value, tree->right);
}
}
return tree;
}
int main(int argc, char** argv)
{
Tree* tree = NULL;
int in;
while (scanf("%d", &in) != EOF) {
tree = addToTree(in, tree);
}
return 0;
}

Resources