110 lines
2.9 KiB
C++
110 lines
2.9 KiB
C++
|
#include "bintree.hpp"
|
||
|
#include "stack.hpp"
|
||
|
#include <time.h>
|
||
|
#include <iostream>
|
||
|
#include <string>
|
||
|
|
||
|
class BST : binTree<int>
|
||
|
{
|
||
|
private:
|
||
|
binNodeArray(int) p;
|
||
|
|
||
|
public:
|
||
|
BST(int num)
|
||
|
{
|
||
|
srand(time(NULL));
|
||
|
int temp = rand() % 1440;
|
||
|
_root->data = temp;
|
||
|
_root->pos = "root";
|
||
|
std::cout << _root->pos;
|
||
|
printf("-%02d:%02d \n", temp / 60, temp % 60);
|
||
|
|
||
|
for (int i = 0; i < num - 1; i++)
|
||
|
{
|
||
|
temp = rand() % 1440;
|
||
|
p = root();
|
||
|
std::string position;
|
||
|
while (temp != -1)
|
||
|
{
|
||
|
if (temp < (p->data))
|
||
|
{
|
||
|
if (hasLC(p))
|
||
|
{
|
||
|
p = p->lc;
|
||
|
position.append("0");
|
||
|
}
|
||
|
|
||
|
else
|
||
|
{
|
||
|
position.append("0");
|
||
|
addLC(p, temp);
|
||
|
p->lc->pos = position;
|
||
|
std::cout << position;
|
||
|
printf("-%02d:%02d \n", temp / 60, temp % 60);
|
||
|
temp = -1;
|
||
|
}
|
||
|
}
|
||
|
else if (temp > (p->data))
|
||
|
{
|
||
|
if (hasRC(p))
|
||
|
{
|
||
|
p = p->rc;
|
||
|
position.append("1");
|
||
|
}
|
||
|
|
||
|
else
|
||
|
{
|
||
|
position.append("1");
|
||
|
addRC(p, temp);
|
||
|
p->rc->pos = position;
|
||
|
std::cout << position;
|
||
|
printf("-%02d:%02d \n", temp / 60, temp % 60);
|
||
|
temp = -1;
|
||
|
}
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
i--;
|
||
|
temp = -1;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
void trav_level()
|
||
|
{
|
||
|
Queue<binNodeArray(int)> q;
|
||
|
q.enqueue(root());
|
||
|
while (!q.empty())
|
||
|
{
|
||
|
|
||
|
binNodeArray(int) node = q.dequeue();
|
||
|
std::cout << node->pos;
|
||
|
printf("-%02d:%02d \n", node->data / 60, node->data % 60);
|
||
|
|
||
|
if (hasLC(node))
|
||
|
q.enqueue(node->lc);
|
||
|
if (hasRC(node))
|
||
|
q.enqueue(node->rc);
|
||
|
}
|
||
|
}
|
||
|
bool searchPath(binNodeArray(int) root, binNodeArray(int) target, Stack<binNodeArray(int)> *s)
|
||
|
{
|
||
|
if (root == NULL)
|
||
|
return false;
|
||
|
s->push(root);
|
||
|
if (root->data == target->data)
|
||
|
return true;
|
||
|
|
||
|
bool flag = false;
|
||
|
//先去左子树找
|
||
|
if (root->lc != NULL)
|
||
|
flag = searchPath(root->lc, target, s);
|
||
|
//左子树找不到并且右子树不为空的情况下才去找
|
||
|
if (!flag && root->rc != NULL)
|
||
|
flag = searchPath(root->rc, target, s);
|
||
|
//左右都找不到,弹出栈顶元素
|
||
|
if (!flag)
|
||
|
s->pop();
|
||
|
return flag;
|
||
|
}
|
||
|
};
|