walk the tree with stack backend

This commit is contained in:
2023-07-13 23:27:20 -07:00
parent 8ab4d74042
commit fbf4af239d

View File

@@ -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);
}