I'm in the middle of writing a C++ program which will eventually sort data, using a tree. I would like to swap a child with its parent if the child's value (could be anything, using a template) is less than the parent's. however, I have become stuck when trying to swap the two. I would like to swap all of the private variables except for 'tree *parent', as that must remain at the same node when everything else changes.
My class is as follows:
template <class data_t> class tree {
data_t val;
tree *lchild, *rchild; //point to children
tree *right, *left; //point to nodes in the same row, right/left
tree *parent; //points to parent
int iam; //defines state (LCHILD (0), RCHILD (1) or ROOT (2)
public:
tree(data_t v) { val=v; lchild=rchild=left=right=0; iam=ROOT; parent=this;}
void add(tree *node);
tree *getnextl() { return lchild; }
tree *getnextr() { return rchild; }
tree *getnextn() { tree *t_parent=parent;
if(!t_parent->rchild) return t_parent;
else if(t_parent->right) return t_parent->right;
else {
while(t_parent->left)
t_parent=t_parent->left;
return t_parent->lchild;}}
tree *getleft() { return left; }
tree *getright() { return right; }
data_t getval() { return val; }
data_t readtop();
void move_up();
};
And the start of the desired move_up() function:
template <class data_t> void tree<data_t>::move_up()
{
if(parent->getval()>val) {
//?????
}
}
The move_up() function is be called at the end of the new tree function, which is called to create each node.
I'd be very grateful for any advice.