first try, looks bad, but working the second pass will be better

This commit is contained in:
Emanuel Rodriguez 2023-07-16 01:19:08 -07:00
parent 755f16877d
commit bed65ad722
1 changed files with 57 additions and 16 deletions

View File

@ -1,18 +1,7 @@
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
/* Set up data structures to be able to support the breadth first search of a tree */
typedef struct QNode {
int value;
struct QNode* next;
} QNode;
typedef struct Q {
QNode* head;
QNode* tail;
int length;
} Q;
typedef struct TreeNode {
int value;
struct TreeNode* left;
@ -23,6 +12,18 @@ typedef struct Tree {
TreeNode* root;
} Tree;
/* Set up data structures to be able to support the breadth first search of a tree */
typedef struct QNode {
TreeNode* tnode; // this is the value of the QNode
struct QNode* next;
} QNode;
typedef struct Q {
QNode* head;
QNode* tail;
int length;
} Q;
TreeNode* new_tree_node(int value) {
TreeNode* node = malloc(sizeof(TreeNode));
node->left = NULL;
@ -32,10 +33,10 @@ TreeNode* new_tree_node(int value) {
return (node);
}
QNode* new_qnode(int value) {
QNode* new_qnode(TreeNode* tnode) {
QNode* node = malloc(sizeof(QNode));
node->next = NULL;
node->value = value;
node->tnode = tnode;
return (node);
}
@ -46,6 +47,15 @@ Tree* new_tree(TreeNode* root) {
return (tree);
}
Q* new_Q() {
Q* q = malloc(sizeof(Q));
q->head = NULL;
q->tail = NULL;
q->length = 0;
return (q);
}
void add_child_left(TreeNode* parent, TreeNode* node) {
if (parent->left != NULL) {
printf("ERROR: left child is non-empty\n");
@ -78,11 +88,13 @@ void q_add_node(Q* q, QNode* node) {
}
// always remove from head
void q_remove_node(Q* q) {
QNode* n = q->head;
TreeNode* q_remove_node(Q* q) {
QNode* n = q->head;
TreeNode* tnode_at_head = n->tnode;
q->head = n->next;
q->length--;
free(n);
return (tnode_at_head);
}
/*
@ -92,6 +104,31 @@ void q_remove_node(Q* q) {
*/
bool bf_search(Tree tree, int value) {
// start by adding th eroot of tree to the q
Q* search_path = new_Q();
QNode* n = new_qnode(tree.root);
q_add_node(search_path, n);
TreeNode* current_value;
while (search_path->length > 0) {
current_value = q_remove_node(search_path);
if (current_value->value == value) {
free(search_path);
return (true);
}
if (current_value->left != NULL) {
q_add_node(search_path, new_qnode(current_value->left));
}
if (current_value->right != NULL) {
q_add_node(search_path, new_qnode(current_value->right));
}
}
free(search_path);
return (false);
}
int main() {
TreeNode* root = new_tree_node(10);
Tree* tree = new_tree(root);
@ -104,4 +141,8 @@ int main() {
add_child_left(root->right, new_tree_node(88));
add_child_right(root->right, new_tree_node(14));
bool answer;
answer = bf_search(*tree, 90);
printf("the answer is %d\n", answer);
}