感觉自己递归掌握的太差了,感觉万事皆可递归,很难理解递归,还要好好琢磨一下
https://blog.csdn.net/u013505811/article/details/94603773
这个大佬讲解了这个代码中递归原理,值得学习
#include<iostream>
using namespace std;
typedef struct node* tree;
struct node{
int data;
tree left;
tree right;
};
tree turnleft(tree root){
tree t=root->right;
root->right=t->left;
t->left=root;
return t;
}
tree turnright(tree root){
tree t=root->left;
root->left=t->right;
t->right=root;
return t;
}
tree leftright(tree root){
root->left=turnleft(root->left);
return turnright(root);
}
tree rightleft(tree root){
root->right=turnright(root->right);
return turnleft(root);
}
int getheight(tree root){
if(root==NULL)return 0;
return max(getheight(root->left),getheight(root->right))+1; //这个递归!!!
}
tree insert(tree root,int x){
if(root==NULL){
root=new node;
root->data=x;
root->left=root->right=NULL;
}else if(x<root->data){
root->left=insert(root->left,x);
if(getheight(root->left)-getheight(root->right)==2)
root=x<root->left->data?turnright(root):leftright(root);
}else if(x>root->data){
root->right=insert(root->right,x);
if(getheight(root->left)-getheight(root->right)==-2)
root=x>root->right->data?turnleft(root):rightleft(root);
}
return root;
}
int main() {
int n, x;
scanf("%d", &n);
tree root = NULL;
for(int i = 0; i < n; i++) {
scanf("%d", &x);
root = insert(root, x);
}
printf("%d", root->data);
return 0;
}
二刷了还是感觉很难,总结一下LL LR RR RL这几个是表示新插入结点的位置,不是代表旋转的方向,如果又忘了旋转看这个网站,这题可以理解加背诵的方式记忆。
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int data;
node* left;
node* right;
};
int getHeight(node* root)
{
if (root == NULL)
return 0;
return max(getHeight(root->left), getHeight(root->right)) + 1;
}
node* LL(node* root)
{
node* t = root->left;
root->left = t->right;
t->right = root;
return t;
}
node* RR(node* root)
{
node* t = root->right;
root->right = t->left;
t->left = root;
return t;
}
node* LR(node* root)
{
root->left = RR(root->left);
return LL(root);
}
node* RL(node* root)
{
root->right = LL(root->right);
return RR(root);
}
node* insert(node* root, int x)
{
if (root == NULL)
{
root = new node;
root->data = x;
root->left = root->right = NULL;
}
else if (x < root->data)
{
root->left = insert(root->left, x);
if (getHeight(root->left) - getHeight(root->right) == 2)
{
if (x < root->left->data)
root = LL(root);
else
root = LR(root);
}
}
else if (x > root->data)
{
root->right = insert(root->right, x);
if (getHeight(root->right) - getHeight(root->left) == 2)
{
if (x > root->right->data)
root = RR(root);
else
root = RL(root);
}
}
return root;
}
int main()
{
int n,x; cin >> n;
node* root = NULL;
for (int i = 0; i < n; i++)
{
cin >> x;
root = insert(root, x);
}
cout << root->data << endl;
}