I want to build a function that receives a tree, and finds the address of a leaf that has a specific value.
typedef struct treeNode {
int data;
struct treeNode* parent;
struct treeNode* left;
struct treeNode* right;
} TreeNode;
typedef struct tree {
TreeNode* root;
List leafList;
} Tree;
function:
TreeNode* findParent(Tree tr, int parentData, int branchSelect)
{
TreeNode* ans = createNewTreeNode(0, NULL, NULL);
ans = findParentRec(tr.root, parentData, branchSelect);
return ans;
}
// BUG TO CHECK: WHY MY OUTPUT IS AN EMPTY TREENODE ?!?!?!??!?!?!??!?!?
TreeNode* findParentRec(TreeNode* tr, int parentData, int branchSelect)
{
if (tr == NULL)
{
return;
}
else if (tr->data == parentData)
{
if ((branchSelect == LEFT && tr->left == NULL) || (branchSelect == RIGHT && tr->right == NULL))
{
return tr;
}
else
{
tr = findParentRec(tr->left, parentData, branchSelect);
tr = findParentRec(tr->right, parentData, branchSelect);
}
}
else
{
tr = findParentRec(tr->left, parentData, branchSelect);
tr = findParentRec(tr->right, parentData, branchSelect);
}
}
For example, we have a tree that has a leaf, with data of "20". I'm recursively trying to find it, and when I found (the data HAS to be somewhere in the tree), I want to return it. The problem is, when I find my data and return it, the value that I receive in
ans = findParentRec(tr.root, parentData, branchSelect);
is an empty treenode.
For example:
My goal is to find "17" in this tree. But when I find it, my output in ans is a treenode with data "0" or 1. BUT my recursive program DO find the specific treenode, and returns it.
Where am I wrong here? How can I change the program that will return me the actual TreeNode* that I need?
Big thanks in advance.