PTA L3-010 是否完全二叉搜索树

题面

在这里插入图片描述

题解

  1. 给定序列,我们建立一颗二叉搜索树,这里用数组存树(根节点为n,那么左儿子为2n,右儿子为2n+1),建树过程,我们每次从根节点开始遍历,遇到大于根节点的就向左递归,否则向右递归,同时我们更新maxn(用来记录最后一个节点所在数组的下标),这样一颗树就建好了
  1. 对于层序遍历,我们直接按数组下标输出即可,判断是否为完全二叉树,我们只需要看前n个点是否在数组前n个位置即可

代码

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

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/115132280