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
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
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
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401