平衡二叉树平衡调整代码
Posted haleypei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了平衡二叉树平衡调整代码相关的知识,希望对你有一定的参考价值。
#include <iostream> using namespace std; struct node { int val; struct node *left, *right; }; node *rotateLeft(node *root) {//左旋 可以记下来 余下都可反推 node *t = root->right; root->right = t->left; t->left = root; return t; } node *rotateRight(node *root) {//右旋 node *t = root->left; root->left = t->right; t->right = root; return t; } node *rotateLeftRight(node *root) {//先左子树左旋在整体右旋 root->left = rotateLeft(root->left); return rotateRight(root); } node *rotateRightLeft(node *root) {//先右子树右旋在整体左旋 root->right = rotateRight(root->right); return rotateLeft(root); } int getHeight(node *root) {//获取二叉树高度,用于判断时候需要平衡调整 if(root == NULL) return 0; return max(getHeight(root->left), getHeight(root->right)) + 1; } node *insert(node *root, int val) {//此为二叉排序树的插入算法加入平衡调整 if(root == NULL) { root = new node(); root->val = val; root->left = root->right = NULL; } else if(val < root->val) { root->left = insert(root->left, val); if(getHeight(root->left) - getHeight(root->right) == 2)//左右子树不平衡时 root = val < root->left->val ? rotateRight(root) : rotateLeftRight(root); } else { root->right = insert(root->right, val); if(getHeight(root->left) - getHeight(root->right) == -2) root = val > root->right->val ? rotateLeft(root) : rotateRightLeft(root); } return root; } int main() { int n, val; scanf("%d", &n); node *root = NULL; for(int i = 0; i < n; i++) { scanf("%d", &val); root = insert(root, val); } printf("%d", root->val); return 0; }
以上是关于平衡二叉树平衡调整代码的主要内容,如果未能解决你的问题,请参考以下文章