0
Good evening, folks. I am trying to implement a binary tree with methods to insert(Insert,insertLeft and insertRight) and print (print).
All goes well until I try to insert a knot in the tree through the Insert method, i can create the no and assign a value to its value variable, but when trying to print the tree nothing appears, the root pointer always ends up pointing to NULL.
Thank you in advance
Follow the code:
class NodeTree {
public:
int value;
NodeTree * left;
NodeTree * right;
NodeTree() {
value = 0;
}
};
#include "NodeTree.h"
#include <iostream>
using namespace std;
class BinaryTree {
public:
NodeTree * root;
BinaryTree() {
root = NULL;
}
bool isEmpty() {
return root == NULL;
}
void makeEmpty() {
root = NULL;
}
void insert(int opcao,int num) {
NodeTree * node = new NodeTree;
node->value = num;
if (opcao == 1) {
insertRigth(node,root);
}
if (opcao == 2) {
insertLeft(node,root);
}
}
void insertRigth(NodeTree * node1,NodeTree * root1) {
if (root1 == NULL) {
node1->right = NULL;
node1->left = NULL;
root1 = node1;
}
else {
insertRigth(node1,root1->right);
}
}
void insertLeft(NodeTree * node1,NodeTree * root1) {
if (root1 == NULL) {
node1->right = NULL;
node1->left = NULL;
root1 = node1;
}
else {
insertLeft(node1,root1->left);
}
}
void print(NodeTree * obj) {
if (obj == NULL) {
cout << "A arvore esta vazia, nao e possivel imprimir\n";
return;
}
print(obj->left);
cout << obj->value << endl;
print(obj->right);
}
};
#include "BinaryTree.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
BinaryTree arvore;
int sentinela = 0;
int opcao;
int numero;
while (sentinela != 3) {
system("cls");
cout << "Opcoes da Arvore Binaria:\n\n1-Inserir\n2-Exibir em Ordem\n3-Sair\n\nOpcao desejada:";
cin >> sentinela;
if (sentinela == 1) {
system("cls");
cout << "Deseja inserir o elemento em qual lado ? 1-Direita / 2-Esquerda: ";
cin >> opcao;
cout << "Digite um numero:";
cin >> numero;
arvore.insert(opcao, numero);
}
if (sentinela == 2) {
system("cls");
arvore.print(arvore.root);
system("PAUSE");
}
}
return 0;
}
Very obg for the help Mario ! I used the second option that Oce passed and it worked !
– Igor PTZ