Root of AVL Tree(平衡二叉树的调整)(借鉴)

感觉自己递归掌握的太差了,感觉万事皆可递归,很难理解递归,还要好好琢磨一下
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;

}




原文地址:https://www.cnblogs.com/Hsiung123/p/13110001.html