码迷,mamicode.com
首页 > 其他好文 > 详细

浙大保研2019年上机题 7-3 Is It An AVL Tree (25分)

时间:2020-06-26 14:44:26      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:positive   else   named   pre   ever   null   pac   new   tin   

7-3 Is It An AVL Tree (25分)

In computer science, an AVL tree (Georgy Adelson-Velsky and Evgenii Landis‘ tree, named after the inventors) is a self-balancing binary search tree. It was the first such data structure to be invented. In an AVL tree, the heights of the two child subtrees of any node differ by at most one. (Quoted from wikipedia)

For each given binary search tree, you are supposed to tell if it is an AVL tree.

Input Specification:

Each input file contains several test cases. The first line gives a positive integer K (≤10) which is the total number of cases. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary search tree. The second line gives the preorder traversal sequence of the tree with all the keys being distinct. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in a line "Yes" if the given tree is an AVL tree, or "No" if not.

Sample Input:

3
7
50 40 36 48 46 62 77
8
50 40 36 48 46 62 77 88
6
50 40 36 48 46 62

Sample Output:

Yes
No
No

判别AVL,本题给出一个二叉排序树的先序序列,按照先序插入,求出该二叉排序树是否是AVL(我们仅仅需要进行判定,该AVL是否每个节点平衡因子都是小于1的,用递归来判定即可)

#include <iostream>
#include <vector>
using namespace std;
struct node {
   int data;
   node *left, *right;
   node(int d): data(d), left(NULL), right(NULL) {}
};
node* insert(node* n, int data) {
   if(n == NULL) n = new node(data);
   else if(data < n->data) n->left = insert(n->left, data);
   else n->right = insert(n->right, data);
   return n;
}
int getHeight(node* n) {
   if(n == NULL) return 0;
   return max(getHeight(n->left), getHeight(n->right)) + 1;
}
bool judgeAVL(node* n) {
   if(n == NULL) return true;
   if(abs(getHeight(n->left) - getHeight(n->right)) > 1) return false;
   return judgeAVL(n->left) && judgeAVL(n->right);
}
int main() {
   int K, N, tmp;
   scanf("%d", &K);
   while(K--) {
       scanf("%d", &N);
       node *n = NULL;
       for(int i = 0; i < N; i++) {
           scanf("%d", &tmp);
           n = insert(n, tmp);
       }
       printf("%s\n", judgeAVL(n) ? "Yes": "No");
   }
   return 0;
}

浙大保研2019年上机题 7-3 Is It An AVL Tree (25分)

标签:positive   else   named   pre   ever   null   pac   new   tin   

原文地址:https://www.cnblogs.com/littlepage/p/13194704.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!