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
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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
Solved Threads: 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
Solved Threads: 2,590
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
Solved Threads: 1,055
Skill Endorsements: 37

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0663 seconds using 2.76MB