Here's the node definition:
struct node{
int data;
stuct node * left;
struct node * right;
};
What I am trying to do is list all the nodes that point to an ancestor node. After posting the wrong solution and taking advice from the answers, my new solution is:
Recursively go through the binary tree. Add the current node to an array of nodes and then check if the children of the current node point to any of the previous ancestor nodes.
The default case is the node being NULL. If that happens the function returns.
How it is supposed to work:
Adds the node to the array
Checks if the left child is NULL.
If not, it compares the child to each of the previous nodes.
If it finds a fault, it reports it.
If not, it calls the function with the child as the argument.
Repeat until finished. (Does same for rhs of binary tree)
Questions:
- Is an array the best thing to store the nodes?
- Does this work? for (i = 0; i < sizeof(arrOfNodes) / sizeof(node); i++)
- Because the function is recursive, the array and the array index can't be initialized inside the function (or can they be?) so should they be global?
- Would it be better to have two arrays? (one for the LHS and one for the RHS)
The code:
void findFault(node * root){
if (root == NULL){
return;
}
arrOfNodes[index++] == root; // array of nodes
if (root->left != NULL){
for (i = 0; i < sizeof(arrOfNodes) / sizeof(node); i++){
if (ar[i] == root->left){
printf("%d", root->left);
return;
}
}
findFault(root->left);
} else return;
if (root->right != NULL){
for (i = 0; i < sizeof(ar) / sizeof(node); i++){
if (ar[i] == root->right){
printf("%d", root->right);
return;
}
}
findFault(root->right);
} else return;
}