Whether PTA L3-010 is a complete binary search tree

Topic

Insert picture description here

answer

  1. Given a sequence, we build a binary search tree, where we use an array to store the tree (the root node is n, then the left son is 2n, and the right son is 2n+1). In the tree building process, we start traversing from the root node each time, Recurse to the left if it encounters a node greater than the root, otherwise recurse to the right, and at the same time we update maxn (used to record the subscript of the array where the last node is located), so that a tree is built
  1. For layer sequence traversal, we can directly output according to the array index to determine whether it is a complete binary tree. We only need to see whether the first n points are in the first n positions of the array.

Code

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1e5 + 10;

int n, x;
int tree[N];

int main() {
    
    

    cin >> n;
    int maxn = 0;
    for (int i = 0; i < n; i++) {
    
    
        cin >> x;
        int now = 1;   //每次从根节点插入
        while (tree[now]) {
    
    
            if (x > tree[now]) {
    
    
                now = now * 2;
            } else {
    
    
                now = now * 2 + 1;
            }
        }
        tree[now] = x;
        if (now > maxn) maxn = now;
    }

    bool flag = true;
    cout << tree[1];
    for (int i = 2; i <= maxn; i++) {
    
    
        if (tree[i]) cout << " " << tree[i];
        else flag = false;  
    }
    cout << endl;
    if (flag) cout << "YES" << endl;
    else cout << "NO" << endl;

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/115132280