算法笔记》9.5小节——数据结构专题(2)

编程入门 行业动态 更新时间:2024-10-09 01:22:09

算法笔记》9.5小节——<a href=https://www.elefans.com/category/jswz/34/1769880.html style=数据结构专题(2)"/>

算法笔记》9.5小节——数据结构专题(2)

《算法笔记》9.5小节——数据结构专题(2)->平衡二叉树(AVL)

#include<cstdio>
#include<math.h>
#include<algorithm>
using namespace std;struct node {int data,height;node* lchild;node* rchild;
};
node* newNode(int v) {node* Node = new node;Node->data = v;Node->height = 1;Node->lchild = NULL;Node->rchild = NULL;return Node;
}
int getHeight(node* root) {if (root == NULL) return 0;else return root->height;
}
int getBalanceFactor(node* root) {return getHeight(root->lchild) - getHeight(root->rchild);
}
void updataHeight(node* root) {root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
void R_rotate(node* &root) {node* temp = root->lchild;root->lchild = temp->rchild;temp->rchild = root;updataHeight(root);updataHeight(temp);root = temp;
}
void L_rotate(node* &root) {node* temp = root->rchild;root->rchild = temp->lchild;temp->lchild = root;updataHeight(root);updataHeight(temp);root = temp;
}
void insert(node*& root, int v) {if (root == NULL) {root = newNode(v);return;}if (v < root->data) {insert(root->lchild, v);updataHeight(root);if (getBalanceFactor(root) == 2) {if (getBalanceFactor(root->lchild) == 1) {R_rotate(root);}if (getBalanceFactor(root->lchild) == -1) {L_rotate(root->lchild);R_rotate(root);}}}else {insert(root->rchild, v);updataHeight(root);if (getBalanceFactor(root)==-2) {if (getBalanceFactor(root->rchild) == -1) {L_rotate(root);}if (getBalanceFactor(root->rchild) == 1) {R_rotate(root->rchild);L_rotate(root);}}}
}
int query(int v, node* root) {if (root == NULL) return 0;if (root->data == v) return 1;if (v < root->data) query(v, root->lchild);else query(v, root->rchild);
}
int main() {int n, m,t;while (scanf("%d %d", &n, &m) != EOF) {node* root=NULL;for (int i = 0; i < n; i++) {scanf("%d", &t);insert(root, t);}for (int i = 0; i < m; i++) {scanf("%d", &t);printf("%d\n",query(t, root));}}
}

更多推荐

算法笔记》9.5小节——数据结构专题(2)

本文发布于:2024-03-23 15:06:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1739582.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据结构   小节   算法   笔记   专题

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!