Search code examples
ctreebreadth-first-search

Try to build a Breadth First Search algorithm for normal tree in C


I try to build a Breadth First Search algorithm for normal tree, which one node can have multiple(could more than two) children.
The main idea of my algorithm is that I go through all the first-kid, and then go through their right-brother by the get() function recursively. All results are stored in a 2-dimentional *char array arr.

  1. traveling all the way down :row++;col=0
  2. going right for brothers :col++
  3. going up and repeat step2.
    (It's seems like I lost the relationship between father and children when store them into the 2-D array, how can I remain it) If every goes well(which is actually not, gcc reports no problem but no output), the output is supposed to be like:
A
B C D
E F G

the tree struct:

struct node *head;
struct node { 
    struct node *firstKid;
    struct node *rightBro;
    char *token; 
};

the main function:I ignore the creat-tree function for all the parameters are passed from another program.

int main() {
    int m=100,n=100;
    // creat-tree function ignored here, the root of the tree  would be head(used in get()func

    char ***arr = (char ***)malloc(n*sizeof(char **));
    for(int i=0;i<n;i++) arr[i] = (char **)malloc(m*sizeof(char*));
    get(head,0,0,arr);
    for(int i=0;i<10;i++){
        for(int j=0;j<10;j++){
            printf("%s",arr[i][j]);
        }
    }

}

my iterator:

void get(struct node *node,int row,int col,char ***arr){ 
    struct node *kid;
    struct node *bro;
    if(node!=NULL){
        arr[row][col]=node->token;
        row=row+1;col=0;
        if(node->firstKid)get(node->firstKid,row,col,arr);
        else{
            bro = node->rightBro;
            while(bro!=NULL){
                col ++;
                arr[row][col]=bro->token;
                bro = node->rightBro;
            }
        }
    }
}

Solution

  • Breadth-first traversal:

    1. Create a to-visit queue.
    2. Add the root to the queue.
    3. While the queue isn't empty,
      1. Dequeue a node.
      2. Visit the dequeued node.
      3. Add the node's children to the queue.

    A search is the same, except you exit the loop once you find the node of interest.

    You have no queue (or anything serving that purpose). Your general approach is flawed. In fact, you are performing a partial depth-first traversal by using a stack (through recursion) instead of a queue.


    I didn't address the specific problem because you'll have to rewrite the code and because you failed to provide a demonstration of the problem.