20.7 Printing a Tree

I l @ ve RuBoard

Despite the complex nature of a tree structure, it is easy to print. Again we use recursion. The printing algorithm is:

  1. For the null tree, print nothing.

  2. Print the data that comes before this node (left tree).

  3. Print this node.

  4. Print the data that comes after this node (right tree).

The code for printing the tree is:

 void tree::print_one(node *top)  {      if (top == NULL)          return;                 // Short tree      print_one(top->left);      std::cout << top->word << '\n';     print_one(top->right);  }  void tree::print(  ) {      print_one(root); } 
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net