15

I'm trying to print binary tree

void print_tree(Node * root,int level )
 {
    if (root!=NULL)  
    {  
        cout<< root->value << endl;
    }
    //...
}

How can I indent output in order to indent each value with level '-' chars.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Fantomas
  • 1,495
  • 4
  • 12
  • 21

3 Answers3

32

You can construct a string to contain a number of repitions of a character:

std::cout << std::string(level, '-') << root->value << std::endl;
Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
2

cout has special characters, below are two:

'\t' - tab
'\n' - new line

Hope it helped.

vinnybad
  • 2,102
  • 3
  • 19
  • 29
1

You also can indent with columns, and think about first column size, then second column size and etc. You can find longest name in every column and then set width for all items in this column with padding and align you wish. You can do it dynamically first search items size, then select width, or you can do it statically like:

#include <iomanip>
#include <iostream>
#include <sstream>

void print_some()
{
    using namespace std;
    stringstream ss;
    ss << left << setw(12) << "id: " << tank_name << '\n';
    ss << left << setw(12) << "texture: " << texture_name << '\n';
    ss << left << setw(12) << "uv_rect: ";
    // clang-format off
    ss << left <<setprecision(3) << fixed
       << setw(7) << r.pos.x << ' '
       << setw(7) << r.pos.y << ' '
       << setw(7) << r.size.x << ' '
       << setw(7) << r.size.y << '\n';
    // clang-format on
    ss << left << setw(12) << "world_pos: " << pos.x << ' ' << pos.y << '\n';
    ss << left << setw(12) << "size: " << size.x << ' ' << size.y << '\n';
    ss << left << setw(12) << "angle: " << angle << '\n';
}

The output may look like:

id:         tank_spr
texture:    tank.png
uv_rect:    0.300   0.500   0.500   0.500  
world_pos:  0.123 0.123
size:       1.000 0.300
angle:      270.000
leanid.chaika
  • 2,143
  • 2
  • 27
  • 30