We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,324 Members — Technology Publication meets Social Media

Connecting 2 tree nodes

Hi all,

Say i have 2 nodes of a tree.

``````struct tree{
int data;
tree* left;
tree* right;
};

NODE1
data = 3;
left = NULL;
right = NULL
``````

and

``````NODE2
data = 6;
left = NULL;
right = NULL
``````

How do i say Node 2 if the left link of node 1 so it creates the start of a tree.

So it looks like

``````    NODE1
/   \
NODE2  NULL
``````

I thought I could say node1->left = &node2; // left = the address of node 2.

Is that right?

Thanks

3
Contributors
2
Replies
2 Hours
Discussion Span
9 Months Ago
Last Updated
3
Views
samohtvii
Newbie Poster
15 posts since Aug 2012
Reputation Points: 0
Skill Endorsements: 0

its customary to name the top of the tree (node 1) "head"

``````struct tree* head = NULL;
``````

After allocating a new tree node check of head == NULL, if it does then just set head = newnode.

Ancient Dragon
Achieved Level 70
Team Colleague
32,275 posts since Aug 2005
Reputation Points: 5,852
Skill Endorsements: 70

I thought I could say node1->left = &node2; // left = the address of node 2.

Is that right?

What happened when you tried it? Didn't it work?

And what The Dragon said is true. Make a pointer named `head` that will point to the first node. That way if the first node has to change it's easy to add a node and relink to the new first node

WaltP
Posting Sage w/ dash of thyme
Team Colleague
11,404 posts since May 2006
Reputation Points: 3,421