From fbf4af239d9fd41368f7ac9b79f09230b0ec6c68 Mon Sep 17 00:00:00 2001 From: ergz Date: Thu, 13 Jul 2023 23:27:20 -0700 Subject: [PATCH] walk the tree with stack backend --- c/binary-tree.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/c/binary-tree.c b/c/binary-tree.c index e4d1648..eb363ec 100644 --- a/c/binary-tree.c +++ b/c/binary-tree.c @@ -43,11 +43,13 @@ void push(Stack* stack, Node* node) { } } -void pop(Stack* stack) { +int pop(Stack* stack) { if (stack->len > 0) { Node* node = stack->head; + int node_val = node->value; stack->head = node->prev; free(node); + return (node_val); } } @@ -109,7 +111,10 @@ void print_binary_tree(IntBinaryNode* node) { } void walk_tree(IntBinaryNode* current_node, Stack* stack) { - if (current_node->left != NULL && current_node->right != NULL) { + if (current_node->left == NULL && current_node->right == NULL) { + printf("looking at value: %d\n", current_node->value); + push(stack, new_node(current_node->value)); + } else { printf("looking at value: %d\n", current_node->value); push(stack, new_node(current_node->value)); @@ -118,6 +123,19 @@ void walk_tree(IntBinaryNode* current_node, Stack* stack) { } } +void print_stack(Stack* stack) { + if (stack->len == 0) { + printf("empty stack\n"); + } else { + printf("[ "); + while (stack->len > 0) { + int res = pop(stack); + printf("%d ", res); + } + printf("]\n"); + } +} + int main() { /* lets create the following tree 12 @@ -140,6 +158,8 @@ int main() { walk_tree(root_node, stack); printf("the len of the stack is %d\n", stack->len); + print_stack(stack); + free(stack); return (0); }