浙大保研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 
#include 
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分))