Write a recursive function PrintPath, to print the path of a node to the root in a binary tree
QUESTION
Write a recursive
function PrintPath, to print the
path of a node to the root in a binary tree (not necessarily a BST) having
integer keys. For example, for the tree
below the function should print: 17, 2, 1, 0, when the function PrintPath(17) is called.
You can assume
there are no duplicate keys in the binary tree.
You also have to implement
the following public method that calls your recursive overloaded PrintPath
method.
void
BinaryTree::PrintPath(int value)
SOLUTION
NOTE: This is one
possible solution and necessarily the best one.
I am sure you can find a better solution
void
BinaryTree::PrintPath(int value)
{
PrintPath(root,value);
}
bool BinaryTree::PrintPath(node *n,int
value)
{
bool
found = false;
if
(n && n->data == value) //base case…value is found
{
found
= true;
}
else
if (n) //note that a base case is implicit here when n is NULL
{
found
= PrintPath(n->left, value);
if
(!found)
found
= PrintPath(n->right,value);
}
if
(found)
cout
<< n->data;
return
found;
}

Comments
Post a Comment