I got this task to compare 2 binary trees which are loaded from 2 *.txt files, where in each file is set of numbers (each number on separate line). I don't have to compare data (numbers) but only structure of the trees.
So far I've done only loading from those .txt files but now i got stuck at algorithm of comparison. I had an idea about going trough trees and comparing existence of nodes something like:
if((node_from_first_tree && node_from_second_tree) == NULL) cout <<"Trees are not the same structure"<<endl;If there is somebody who can help me with it I'll be very grateful :)
Here is my code:
Node.h
#pragma once
class Node
{
public:
Node(int number, Node* parent);
Node(void);
Node(int number);
~Node(void);
Node* right;
Node* left;
Node* parent;
int number;
};
Tree.h
#include "Node.h"
#pragma once
class Tree
{
public:
Tree(int number);
~Tree(void);
Tree();
Node* root;
void insertNode(int number);
};
Tree.cpp
#include "Tree.h"
#include "Node.h"
#include <iostream>
using namespace std;
/*
Tree::Tree(int number)
{
this->root = new Node(number, NULL);
}
*/
Tree::Tree()
{
this->root = new Node(NULL,NULL);
}
Tree::~Tree(void)
{
}
void Tree::insertNode(int number)
{
Node *current = root;
while(1){
if(number < current->number){
cout <<"Going to left branch"<<endl;
if(current->left == NULL){
current->left = new Node(number, current);
cout <<"Inserting new left branch and filling with number: "<< number <<endl;
break;
}
else{
current = current->left;
cout <<"Left branch exists. Current node is left child."<<endl;
continue;
}
}
else if(number > current->number){
cout <<"Going to right branch"<<endl;
if(current->right == NULL){
current->right = new Node(number, current);
cout <<"Inserting new right branch and filling with number: "<< number <<endl;
break;
}
else{
current = current->right;
cout <<"Right branch exists. Current node is right child"<<endl;
continue;
}
}
else
{
break;
}
}
}
Node.cpp
#include "Node.h"
#include <iostream>
Node::Node(void)
{
}
Node::Node(int number, Node* parent)
{
this->number = number;
this->left = NULL;
this->right = NULL;
this->parent = NULL;
}
Node::~Node(void)
{
}
main.cpp
#include "Node.h"
#include "Tree.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
Tree tree1, tree2;
int line;
ifstream file;
ifstream file2;
file.open("file.txt");
file2.open("file2.txt");
if(file.is_open())
{
cout << "**Open file 1**" <<endl;
while(file.good())
{
file >> line;
// cout << line <<endl;
tree1.insertNode(line);
}
}
if(file2.is_open())
{
cout <<endl<<endl<<endl;
cout << "**Open file 2**" <<endl;
while(file2.good())
{
file2 >> line;
// cout << line <<endl;
tree2.insertNode(line);
}
}
file.close();
cout << "**Closing file 1**"<<endl;
file2.close();
cout << "**Closing file 2**"<<endl;
}


Sign In
Create Account

Back to top









