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;
    
    }
    
    
    
    
    
    
  • 相关阅读:
    新手学逆向,调试abexcm1过程
    (原创)渗透某国工业系统
    (原创)对某国的一次渗透
    汇编笔记 RETF
    汇编笔记 CALL(1)
    汇编笔记 RET
    大小写转换
    JDK下载太慢?让国内镜像帮助你
    Win7,docker安装后,创建虚拟机分配不了ip错误 err: exit status 255
    Spring事务传播实践与Spring“事务失效”
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13110001.html
Copyright © 2011-2022 走看看