How to create binary tree with linked lists?

Hi, I need to create a binary tree using linked lists like this:
struct node{
node *left;
int data;
node *right;
};
the *left points to the left child and *right points to the right child.
but when i want to input data ,every node needs name and i don't know how to do this.
Sorry for my bad English. ((-:
Hi.
If you need to assign a name for each node, you can add a
string name;
line inside the node structure.
Be sure to include the <string> header.
Last edited on
Thanks. but i need something to do this:

for(i=0;i<100;i++)
{
node /*i need a name here*/;
cin>>node->data;
}
You can use structs inside structs. Declare a suitable struct that can hold the data you want to store in the binary tree, and then use it as the data type of the "data" member in your node struct.
Don't think of a tree as an array (it's not!) Hence:
1
2
3
for( int i = 0; i < N; i++ )
  ... //loops though a linear structure, from index 0 to N
    // this will not work on tree (or other non-indexed structures 


All trees have a root node, so if you want to traverse a tree you need to do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct node {
  int data;
  node *left, *right;

  void traverse() {
    ... //do something with this node pointer
    if(left)
      left->traverse();
    if(right)
      right->traverse();
  }
};

int main() {
  node root = ... //store the root node in "root"
  root.traverse();
  
  return 0;
}
Thanks everybody. :-))))
Topic archived. No new replies allowed.