Printing Binary Tree

I know how to print a balanced binary tree, I'm just not sure how to print a tree with index values. By index values I mean if I print a list, I want to say that node X is the 5 node or whatever. I don't need to go back and use these index values like arrays to access an element. Just when I'm printing to console, do something like:

1 Node1
2 Node2
3 Node3
4 Node4
...and so on.

I've tried a few different options but my values grow exponentially or other weird things happen.

The function at it's basic:
1
2
3
4
5
6
7
8
9
10
11
void Print (node * x)
{
  if ( x != NULL )
  {
    Print (x->left);
    cout << ....data that needs to be printed
    Print (x->right);
  }

  return;
}


Any ideas?
Check this out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
using namespace std;

struct Node
{
    Node * left;
    Node * right;
    int value;

    Node():left(0),right(0){}

    ~Node()
    {
        if (left) delete left;
        if (right) delete right;
    }
};

void Print (Node * x, int & id)
{
    if (!x) return;

    Print (x->left,id);

    id++;
    cout << id << ' ' << x->value << endl;

    Print (x->right,id);
}

int main()
{
    Node * root=new Node;
    root->value=10;

    root->left=new Node;
    root->left->value=20;

    root->left->left=new Node;
    root->left->left->value=30;

    root->right=new Node;
    root->right->value=40;

    root->right->left=new Node;
    root->right->left->value=50;

    int id=0;

    Print(root,id);

    delete root;

    cin.get();
    return 0;
}
Last edited on
*Bows to your greatness*

Awesome. Thanks m4ster r0shi. I was doing something similar in one of my tries. I feel like an idiot.

Thank you.
Topic archived. No new replies allowed.