Reputation: 145
So, I got a tree like this
a
/ \
b c
/ \ /
d e f
the function have to print:
a
ab
abd
abe
ac
acf
my teacher say that the only argument that I can have is a pointer to the first node. I can't use any other variable including static and global variable.
void print(Node* a)
{
if(a==NULL){return;}
cout<<a->data;
if(a->left!=NULL){print(a->left);}
if(a->right!=NULL){print(a-right);}
}
So far, my program can only print "abdecf". any suggestion?
Upvotes: 0
Views: 4433
Reputation: 7502
What you could is add a parent to the structure that represents a node. Like so -
class Node {
public:
char data;
Node *left;
Node *right;
Node *parent;
};
So now with this modified data structure, you will print at every level the path from the current node to the root, like so -
void print(Node* a)
{
Node *cur = a;
do {
cout << cur->data << ", ";
cur = cur->parent;
} while(cur != NULL);
if(a->left != NULL){
print(a->left);
}
if(a->right != NULL){
print(a->right);
}
}
Upvotes: 1