L3-010 是否完全二叉搜索樹 (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
判斷完全二叉樹:
什麼是完全二叉樹,按我的理解就是,一種殘缺的滿二叉樹(最多就是底層右邊可以缺少幾個節點)。
如果我們在二叉樹的外層補上一層空結點呢(將非空結點的左右孩子給補上)會發生什麼呢?
好了,我就是這樣判斷的
推薦測試用例:
測試點2:5 5 7 4 8 6
測試點3:5 5 7 4 8 3
測試點7:2 2 1
#include<iostream>
#include<string>
#include<map>
#include<queue>
using namespace std;
struct Node {
int left=-1, right=-1;
};
map<int, Node> tree;
void insert(int head, int tmp,int height) { //構造搜索樹
if (head != -1) {
int r = tmp > head ? tree[head].left : tree[head].right;
if (r != -1)
insert(r, tmp,height+1);
else
(tmp > head ? tree[head].left : tree[head].right) = tmp;
}
}
void traverse(int head) {
queue<int> q;
q.push(head);
int key = 0, empty = 0;
cout << head;
while (!q.empty()) {
if (q.front() != -1) {
q.push(tree[q.front()].left);
q.push(tree[q.front()].right);
if (empty) key = 1;
}
else empty = 1; //當出現空結點,後面的必須都是空結點
q.pop();
if(q.front()!=-1&&!q.empty()) //輸出非空結點
cout <<" "<< q.front();
}
cout<<endl<<( key ? "NO" : "YES");
}
int main() {
int n, m, tmp, head;
string link, str;
cin >> n >> head;
for (int i = 1; i < n; i++) {
cin >> tmp;
insert(head, tmp, 1);
}
traverse(head);
return 0;
}