Skip to content

Instantly share code, notes, and snippets.

@felialois
Created November 6, 2012 04:58
Show Gist options
  • Save felialois/4022667 to your computer and use it in GitHub Desktop.
Save felialois/4022667 to your computer and use it in GitHub Desktop.
Tarea Datos 5 ejercicio 6
//
// Tarea 5 ej6.cpp
// Tarea Datos 4
//
// Created by Felipe Alfaro on 11/5/12.
// Copyright (c) 2012 Felipe Alfaro. All rights reserved.
//
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <math.h>
//clase arbol
template <typename E> class BinTree{
private:
E* arreglo;
E root= arreglo[0];
int size;
void insert(const E elem, int indice){
//version privada de insert para la recursion
if (indice>size){
std::cout<<"arbol lleno"<<"\n";
}
else if (arreglo[indice]==-100){
arreglo[indice]=elem;
}
else if (elem>arreglo[indice]){
insert(elem,((2*indice)+2));
}
else if (elem<=arreglo[indice]){
insert(elem,((2*indice)+1));
}
}
public:
BinTree(int _tam){ //constructor
size=_tam;
arreglo= new E[size];
for (int i=0;i<size;i++){
arreglo[i]=-100;
}
}
void setIzquierdo(E elem, int indice){
arreglo[(2*indice)+1]=elem;
}
void setDerecho(E elem, int indice){
arreglo[(2*indice)+2]=elem;
}
// izquierdo (2*indice)+1
//derecho (2*indice)+2
void Insert(E elem){ //version de insert que empieza con la raiz
insert(elem,0);
}
const E Izquierdo(int indice){
if (((2*indice)+1)<size)
return arreglo[(2*indice)+1];
else
return 0;
}
const E Derecho(int indice){
if (((2*indice)+2)<size){
return arreglo[(2*indice)+2];}
else
return 0;
}
const E Hermano(int indice){
if ((indice%2)==0){
return arreglo[indice-1];
}
else
return arreglo[indice+1];
}
void print(){
using namespace std;
for(int i=0;i<size;i++){
if (arreglo[i]!=-100){
cout<<arreglo[i];
cout<<"\n";
if ((Derecho(i)!=-100)&&(Izquierdo(i)!=-100)){
cout<<"hijo derecho: ";
if (Derecho(i)==-100){cout<<"vacio";}
else{cout<<Derecho(i);}
cout<<"\n";
cout<<"hijo izquierdo: ";
if (Izquierdo(i)==-100){cout<<"vacio";}
else{cout<<Izquierdo(i);}
cout<<"\n";}
else{
cout<<"hoja"<<"\n";
}
}
}
}
};
int main(int argc, const char * argv[])
{
BinTree<int>* arbol=new BinTree<int>(15);
arbol->Insert(9);
arbol->Insert(7);
arbol->Insert(8);
arbol->Insert(11);
arbol->Insert(13);
arbol->Insert(12);
arbol->Insert(19);
arbol->Insert(5);
arbol->print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment