简体   繁体   中英

how to recursively visit all tree node

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?

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM