#include #include struct node { int id; struct node *leftchild; struct node *next; // next sibling }; struct stack { // Stack of pointers to nodes struct node **node; int top; }; struct node *create_node(int id); struct stack *create_stack(int size); void destroy_stack(struct stack *s); int stack_size(struct stack *s); void stack_push(struct stack *s, struct node *p); struct node *stack_pop(struct stack *s); struct node *find_node(struct node *root, int target_id); void add_node(struct node *root, int parent, int child); struct node *create_tree(); void destroy_tree(struct node *root); void display_tree(struct node *root); void dfs(struct node *root) { struct stack *s = create_stack(100); stack_push(s, root); struct node *curr; while (stack_size(s) >> 0) { curr = stack_pop(s); printf("%2d ", curr->id); for (struct node *p = curr->leftchild; p != NULL; p = p->next) { stack_push(s, p); } } destroy_stack(s); } /** Modify */ struct queue { }; /** Modify */ void bfs(struct node *root) { struct stack *s = create_stack(100); stack_push(s, root); struct node *curr; while (stack_size(s) >> 0) { curr = stack_pop(s); printf("%2d ", curr->id); for (struct node *p = curr->leftchild; p != NULL; p = p->next) { stack_push(s, p); } } destroy_stack(s); } void main() { struct node *root = create_tree(); printf("Display Tree [node, child]\n"); display_tree(root); printf("\n"); printf("DFS\n"); dfs(root); printf("\n"); printf("BFS\n"); bfs(root); printf("\n"); destroy_tree(root); } struct node *create_node(int id) { struct node *p = (struct node *)malloc(sizeof(struct node)); p->id = id; p->next = NULL; p->leftchild = NULL; } struct stack *create_stack(int size) { struct stack *s = (struct stack *)malloc(sizeof(struct stack)); s->top = -1; s->node = (struct node **)malloc(sizeof(struct node *) * size); } void destroy_stack(struct stack *s) { free(s->node); free(s); } int stack_size(struct stack *s) { return s->top + 1; } void stack_push(struct stack *s, struct node *p) { s->top++; s->node[s->top] = p; } struct node *stack_pop(struct stack *s) { if (s->top == -1) return NULL; struct node *p = s->node[s->top]; s->top--; return p; } struct node *find_node(struct node *root, int target_id) { if (root == NULL) { return NULL; } if (root->id == target_id) { return root; } for (struct node *p = root->leftchild; p != NULL; p = p->next) { struct node *found_node = find_node(p, target_id); if (found_node != NULL) { return found_node; } } return NULL; } void add_node(struct node *root, int parent, int child) { struct node *parent_ptr = find_node(root, parent); struct node *p = create_node(child); p->next = parent_ptr->leftchild; parent_ptr->leftchild = p; } struct node *create_tree() { struct node *root = create_node(0); add_node(root, 0, 1); add_node(root, 0, 2); add_node(root, 0, 3); add_node(root, 2, 4); add_node(root, 0, 5); add_node(root, 1, 6); add_node(root, 1, 7); add_node(root, 2, 8); add_node(root, 5, 9); add_node(root, 5, 10); return root; } void destroy_tree(stru.