zoukankan      html  css  js  c++  java
  • 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;
    
    }
    
    
    
    
    
    
  • 相关阅读:
    php转义和去掉html、php标签函数
    php命令行模式
    php开启新的进程或者线程
    防止便秘的食物
    各种米的营养价值
    select option jquery javascript
    mysql datetime、date、time、timestamp区别
    五脏之对应体液志窍时
    Html简单demo_html列表中进行编辑操作
    mysql sql语句使用技巧
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13110001.html
Copyright © 2011-2022 走看看