B - 数据结构实验之查找二:平衡二叉树
生活随笔
收集整理的這篇文章主要介紹了
B - 数据结构实验之查找二:平衡二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Description
根據給定的輸入序列建立一棵平衡二叉樹,求出建立的平衡二叉樹的樹根。
Input
輸入一組測試數據。數據的第1行給出一個正整數N(n <= 20),N表示輸入序列的元素個數;第2行給出N個正整數,按數據給定順序建立平衡二叉樹。
Output
輸出平衡二叉樹的樹根。
Sample
Input
Output
70Hint
平衡二叉樹詳解
#include<bits/stdc++.h>using namespace std;typedef struct node {int data;struct node *l, *r; } tree;int geth(tree *root) {int de = 0;if(root){int left_depth = geth(root->l);int right_depth = geth(root->r);de = left_depth > right_depth ? left_depth + 1 : right_depth + 1;}return de; } tree *LL(tree *root) {tree *p;p = root->l;root->l = p->r;p->r = root;return p; }tree *RR(tree *root) {tree *p;p = root->r;root->r = p->l;p->l = root;return p; }tree *LR(tree *root) {root->l = RR(root->l);root = LL(root);return root; } tree *RL(tree *root) {root->r = LL(root->r);root = RR(root);return root; } tree *create(tree *root, int k) {if(root == NULL){root = new tree;root->data = k;root->l = NULL;root->r = NULL;}else{if(k < root->data)root->l = create(root->l, k);elseroot->r = create(root->r, k);}if(geth(root->l) - geth(root->r) >= 2){if(geth(root->l->l) > geth(root->l->r))root = LL(root);elseroot = LR(root);}if(geth(root->r) - geth(root->l) >= 2){if(geth(root->r->r) > geth(root->r->l))root = RR(root);elseroot = RL(root);}return root; } int main() {ios::sync_with_stdio(0);int n, k;cin >> n;tree *root = NULL;while(n--){cin >> k;root = create(root,k);}cout << root->data << endl;return 0; }總結
以上是生活随笔為你收集整理的B - 数据结构实验之查找二:平衡二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构实验之查找四:二分查找(递归实现
- 下一篇: C - 数据结构实验之查找三:树的种类统