icp/oer/courses/c-advanced/sections/01-introduction/06-tree/program.c

90 lines
1.7 KiB
C
Raw Normal View History

2018-05-05 22:18:02 +00:00
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int Value;
struct node *Left;
struct node *Right;
}node;
node *alloc_node(int Value, node *Left, node *Right)
{
node *NewNode = malloc(sizeof(node));
NewNode->Value = Value;
NewNode->Left = Left;
NewNode->Right = Right;
return NewNode;
}
// inserts into the right place in the tree
void tree_insert(node *Root, int Value)
{
// TODO: implement this
}
// finds the node with the given value.
// if it doesn't find one return null
node *tree_find(node *Root, int Value)
{
// TODO: implement this
return 0;
}
// deletes the node with the value while remaining sorted
// NOTE: feel free to change the function signiture
void tree_delete(node *Root, int Value)
{
// TODO: implement this
// NOTE: when finding the node to delete,
// keep track of the parent node to rewire
// the pointer when deleting
// NOTE: don't forget to free the memory
}
// prints every member in a sorted way
int tree_print_sorted(node *Root)
{
// TODO: implement this
}
int main(int argc, char **argv)
{
node Root = {};
int Numbers[10] = {9, 128, 3, 1, 42, 9001, 7, 500, 6, 10};
// NOTE: filling the tree with numbers
for(int i = 0 ; i < 10; i++)
{
tree_insert(&Root, Numbers[i]);
}
node *Nine = tree_find(&Root, 9);
int FoundNine = 0;
if(Nine)
{
FoundNine = 1;
node *Left = Nine->Left;
node *Right = Nine->Right;
printf("Found %d with direct child %d and %d\n", Nine->Value, (Left)? Left->Value: 0, (Right)? Right->Value : 0);
}
tree_delete(&Root, 9);
Nine = tree_find(&Root, 9);
if(Nine)
{
printf("Failed to delete %d\n", Nine->Value);
}
else
{
if(FoundNine)
printf("Succesfully deleted 9\n");
}
tree_print_sorted(&Root);
printf("\n");
}