主函数如下,其他文件与本人另一篇博客相同,请自行查看
#include<iostream>
#include<vector>
#include<queue>
#include"node.h"
#include"binarytree.h"
#include"binarytreecode.h"
using namespace std;
int max(int a, int b)
{
return a > b ? a : b;
}
///深度
int deep( node<int> *root)
{
if (root == NULL)
return -1;
else return root->high;
}
node<int> *LL( node<int> *root)
{
node<int> *p = root->left;
root->left = p->right;
p->right = root;
root->high = max(deep(root->left), deep(root->right)) + 1;
return p;
}
struct node<int>*RR(node<int> *root)
{
node<int> *p = root->right;
root->right = p->left;
p->left = root;
root->high = max(deep(root->left), deep(root->right)) + 1;
return p;
}
node<int> *RL( node<int> *root)
{
root->right = LL(root->right);
root = RR(root);
return root;
}
node<int> *LR( node<int> *root)
{
root->left = RR(root->left);
root = LL(root);
return root;
}
node<int> *Insert(node<int> *root, int num)
{
if (!root)
{
root = new node<int>;
root->val = num;
root->high = 0;
root->left = NULL;
root->right = NULL;
}
else
{
if (num < root->val)///数据比根小
{
root->left = Insert(root->left, num);///加到左子树上
///先判断是否要转
if (abs(deep(root->left) - deep(root->right)) > 1)//深度之差大于一就转
{
if (num >= root->left->val)///比左子根大,转两次,即LR
{
root = LR(root);
}
else ///比左子根小,转一次,即LL
{
root = LL(root);
}
}
}
else///比根大
{
root->right = Insert(root->right, num);///加到右子树上
if (abs(deep(root->left) - deep(root->right)) > 1)
{
if (num >= root->right->val)///加到右子树的右边,转一次,RR
{
root = RR(root);
}
else///加到右子树的左边,转两次,RL
{
root = RL(root);
}
}
}
}
root->high = max(deep(root->left), deep(root->right)) + 1;
return root;
}
node<int>* buildTree(vector<int> b) {
node<int> *temp=nullptr;
//temp= Insert(temp, b[0]);
for (int i = 0; i < b.size(); ++i) {
// cout << b[i] << endl;
/* queue <node<int> *> que;
que.push(temp);
while (!que.empty())
{
// cout << "14564568" << endl;
if (que.front()) {
cout << que.front()->val << " ";
que.push(que.front()->left);
que.push(que.front()->right);
}
que.pop();
}
cout << endl;*/
temp=Insert(temp, b[i]);
}
return temp;
}
int main()
{
binarytreecode<int> tre;
int n,temp;
cin >> n;
vector <int> bnum;
// vector <int> mnum;
for (int i = 0; i < n; ++i) {
cin >> temp;
bnum.push_back(temp);
}
// tre.backToHead();
// cout << "dhjfdjldsh" << endl;
tre.setHeadNode(buildTree(bnum));
// tre.printmid(buildTree(bnum, mnum, 0, n - 1, 0, n - 1));
//cout << "djfdsklafdj";
// cout << tre.reHead()->val << endl;
// cout << tre.reHead()->val << endl;
//cout << tre.reHead()->val << endl;
queue <node<int> *> que;
que.push(tre.reHead());
while (!que.empty())
{
// cout << "14564568" << endl;
if (que.front()) {
cout << que.front()->val<<" ";
que.push(que.front()->left);
que.push(que.front()->right);
}
que.pop();
}
//cout << "djfdsklafdj"<<endl;
cin >> n;
return 0;
}
/*
10
1 2 3 4 5 6 7 8 9 0
*/