954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Tree help

So in a binary tree the insertion looks something like this:

void btree::insert(int num)
{
	if(root!=NULL)
	{
		insert(num, root);
	}
	else
	{
		root=new Node;
		root->data=num;
		root->left=NULL;
		root->right=NULL;
	}
}
	
void btree::insert(int num, Node *leaf)
{
	if(num< leaf->data)
	{
		if(leaf->left!=NULL)
		{
			insert(num, leaf->left);
		}
		else
		{
			leaf->left=new Node;
			leaf->left->data=num;
			leaf->left->left=NULL;
			leaf->left->right=NULL;
		}
	}
	else if(num>=leaf->data)
	{
		if(leaf->right!=NULL)
			insert(num, leaf->right);
		else
		{
			leaf->right=new Node;
			leaf->right->data=num;
			leaf->right->left=NULL;
			leaf->right->right=NULL;
		}
	}
}


But how would you insert for an n-ary tree?

JackDurden
Junior Poster in Training
92 posts since Jun 2008
Reputation Points: 10
Solved Threads: 0
 

The same way, except instead of dealing with only two links, you have more than two (usually in an array).

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

It would be better if you divide that nary tree nodes in some hierarchical levels so that it would be helpful in deciding their positions in future.

csurfer
Posting Pro
568 posts since Jan 2009
Reputation Points: 485
Solved Threads: 88
 

So If i had this how would I keep track of the root children?

#include<iostream>
#include<vector>

using namespace std;

class Tree
{
public:
	Tree() { root = NULL; }

	bool isEmpty() const { return root==NULL; }
	void insert(int);
	void remove(int);
	
private:
	struct node
	{
		node *parent;
		vector <node*> children;
		int item;
	};

node* root;
};

void Tree::insert(int num)
{
	if(isEmpty())
	{
		root=new node;
		root->item = num;
	}
	else
	{
		//?
	}

}

int main()
{
return 0;
}
JackDurden
Junior Poster in Training
92 posts since Jun 2008
Reputation Points: 10
Solved Threads: 0
 

Well, do the children need to be in any specific order? If so, you know what to do: keep the vector sorted to maintain that order. That's how you keep track of the nodes.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Or may be a priority array which stores the data in the node for referencing the node and its level or priority in the tree.

csurfer
Posting Pro
568 posts since Jan 2009
Reputation Points: 485
Solved Threads: 88
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You