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
.
row++;col=0
col++
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;
}
}
}
}
Breadth-first traversal:
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.