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

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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章