BFS and DFS For Trees
BFS and DFS For Trees
////////BFS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
while(!isEmpty(&q)) {
TreeNode *t = front(&q); // Get current node
printf("%d ", t->data); // Print its data
dequeue(&q); // Remove it from queue
addChild(n2, n5); // 2 → 5
addChild(n3, n6); // 3 → 6
return 0;
}
4
///////////DFS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
Stack s;
init(&s); // Initialize stack
push(&s, head); // Start from root
while (!isEmpty(&s)) {
TreeNode *t = top(&s);
printf("%d ", t->data); // Visit node
pop(&s);
TreeNode *c = t->firstChild;
while (c) {
children[count++] = c;
c = c->nextSiblings;
}
// Push children onto stack in reverse order so the leftmost
child is processed first
for (int i = count - 1; i >= 0; i--) {
push(&s, children[i]);
}
}
}