1. 程式人生 > >PTA 資料結構——是否完全二叉搜尋樹

PTA 資料結構——是否完全二叉搜尋樹

7-2 是否完全二叉搜尋樹 (30 分)

將一系列給定數字順序插入一個初始為空的二叉搜尋樹(定義為左子樹鍵值大,右子樹鍵值小),你需要判斷最後的樹是否一棵完全二叉樹,並且給出其層序遍歷的結果。

輸入格式:

輸入第一行給出一個不超過20的正整數N;第二行給出N個互不相同的正整數,其間以空格分隔。

輸出格式:

將輸入的N個正整數順序插入一個初始為空的二叉搜尋樹。在第一行中輸出結果樹的層序遍歷結果,數字間以1個空格分隔,行的首尾不得有多餘空格。第二行輸出YES,如果該樹是完全二叉樹;否則輸出NO

輸入樣例1:

9
38 45 42 24 58 30 67 12 51

輸出樣例1:

38 45 24 58 42 30 12 67 51
YES

輸入樣例2:

8
38 24 12 45 58 67 42 51

輸出樣例2:

38 45 24 58 42 12 67 51
NO

思路:根據完全二叉樹的下標性質,我們可以用陣列模擬,這樣可以大大減少程式碼量,也很易於理解

AC程式碼:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include 
<vector> #include <cstdio> #include <malloc.h> #define INF 0x3f3f3f3f #define FRER() freopen("in.txt", "r", stdin) #define FREW() freopen("out.txt", "w", stdout) using namespace std; const int maxn = 2097152 + 5; int n, m, num[maxn]; void insert(int idx) { if(!num[idx]) { num[idx]
= m; return ; } if(m > num[idx]) insert(idx * 2); else insert(idx * 2 + 1); } int main() { cin >> n; for(int i = 0; i < n; ++i) { cin >> m; insert(1); } bool ok = true; int cnt = 0; for(int i = 1; ; ++i) { if(num[i]) { cout << num[i]; ++cnt; if(cnt < n) cout << " "; else { cout << endl; break; } } else ok = false; } if(ok) cout << "YES" << endl; else cout << "NO" << endl; return 0; }