Documente Academic
Documente Profesional
Documente Cultură
Structure
Mugurel Ionu Andreica
Spring 2012
void insert(T x) {
if (pinfo == NULL)
setInfo(x);
else
insert_rec(x);
}
void insert_rec(T x) {
int next_son = rand() % 2;
if (next_son == 0) // left son {
if (left_son == NULL) {
left_son = new BinaryTreeNode<T>;
left_son->pinfo = new T;
*(left_son->pinfo) = x;
left_son->left_son = left_son->right_son
= NULL;
BinaryTreeNode<T>* find(T x) {
BinaryTree<T> *rez;
if (pinfo == NULL)
return NULL;
// Use an equality testing function instead
if ((*pinfo) == x)
return this;
if (left_son != NULL)
rez = left_son->find(x);
else
rez = NULL;
if (rez != NULL)
return rez;
else if (right_son != NULL)
return right_son->find(x);
else {
if (leaf->parent->left_son == leaf)
leaf->parent->left_son = NULL;
else
leaf->parent->right_son = NULL;
leaf->parent = parent;
leaf->left_son = left_son;
leaf->right_son = right_son;
delete this->pinfo;
this->pinfo = leaf->pinfo;
delete leaf;
}
}
void remove() {
BinaryTreeNode<T> *leaf;
// find a leaf in this node's subtree
leaf = findLeaf();
if (this == leaf) {
if (parent == NULL) // this == root
{
if (this->pinfo != NULL) delete this->pinfo;
root->pinfo = NULL; }
else {
if (parent->left_son == this)
parent->left_son = NULL;
else
parent->right_son = NULL;
delete this->pinfo;
delete this;
}}
}
void removeInfo(T x) {
BinaryTreeNode<T> *t = find(x);
if (t != NULL) t->remove();
}
BinaryTreeNode<T>* findLeaf() {
if (left_son == NULL && right_son == NULL)
return this;
int main() {
srand(7290);
BinaryTreeNode<int> *r = new BinaryTreeNode<int>;
// r->setRoot(r);
}
void preOrderTraversal3(int level) {
int i;
for (i = 1; i <= level; i++)
printf("%c", chstack[i]);
printf("* %d\n", (*pinfo)); /* use the correct
format */
chstack[level + 1] = 'L';
if (left_son != NULL)
left_son->preOrderTraversal3(level + 1);
chstack[level + 1] = 'R';
if (right_son != NULL)
right_son->preOrderTraversal3(level + 1);
}
};
r->insert(6);
r->insert(8);
r->insert(1);
r->insert(9);
r->insert(10);
r->insert(4);
r->insert(13);
r->insert(1);
r->insert(12);
r->preOrderTraversal();
printf("___\n");
r->preOrderTraversal2(0);
printf("___\n");