1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
#include "binarysearchtree.h"
BinarySearchTree::BinarySearchTree()
{
m_root = NULL;
}
BinarySearchTree::~BinarySearchTree()
{
}
void BinarySearchTree::insert_node(int number)
{
insert_node(number, m_root);
}
void BinarySearchTree::insert_node(int number, Node*& node)
{
if(node==NULL)
{
node = new Node(number, NULL, NULL);
}
else if( number < node->m_number){
insert_node( number,node->m_left );
}
else if(number>node->m_number){
insert_node(number, node->m_right);
}
}
void BinarySearchTree::print()
{
vector<Node*> myvector;
int height = find_height(m_root);
if(m_root!=NULL)
{
myvector.push_back(m_root);
print_tree_graph(myvector, height, 1);
}
}
void BinarySearchTree::print_tree_graph(vector<Node*> &node, int height, int level)
{
int floor = height-level;
int edge_line = pow(2, max((floor-1), 0));
int first_space = pow (2, floor) -1;
int between_space = pow(2, (floor+1))-1;
print_space(first_space);
vector<Node*> myvector;
for (unsigned int i=0; i<node.size(); i++)
{
if(node.at(i)!=NULL)
{
cout<<node.at(i)->m_number;
myvector.push_back(node.at(i)->m_left);
myvector.push_back(node.at(i)->m_right);
}else{
myvector.push_back(NULL);
myvector.push_back(NULL);
print_space(1);
}
print_space(between_space);
}
cout<<"myvector: " <<myvector.size()<<endl;
for(unsigned int i=0; i<myvector.size(); i++)
cout<<myvector[i]->m_number <<" ";
cout<<"\n";
for(int i=1; i<=edge_line; i++)
{
for(unsigned int j=0; j< node.size(); j++)
{
print_space(first_space-i);
if(node[j]==NULL)
print_space(edge_line+edge_line+1);
if(node[j]->m_left!=NULL)
cout<<"/";
else
print_space(1);
print_space(i + i -1);
if(node[j]->m_right!=NULL)
cout<<"\\";
else
print_space(1);
print_space(edge_line + edge_line -i);
}
cout<<"\n";
}
level++;
print_tree_graph(myvector, height, level);
myvector.clear();
node.clear();
}
void BinarySearchTree::print_space(int count)
{
for(int i=0; i<count; i++)
cout<<" ";
}
int BinarySearchTree::find_height()
{
return find_height(m_root);
}
int BinarySearchTree::find_height(Node*& node)
{
if(node == NULL)
return 0;
else
return max( find_height(node ->m_left) +1, find_height(node->m_right)+1);
}
int BinarySearchTree::max(int a, int b)
{
return (a >= b ? a : b);
}
|