PAT(Advanced)甲級1110 Complete Binary Tree C++實現
題目鏈接
題目大意
從0到N-1個節點,給定每個節點的左右孩子,求給定二叉樹是否爲完全二叉樹,若是則輸出YES
以及最右邊的葉子節點的序號,否則輸出NO
以及根節點序號
算法思路
根據題意要求和輸入數據,先找到二叉樹根節點,即沒有父親節點的節點,根據完全二叉樹性質和層序遍歷定義,對完全二叉樹進行層序遍歷,將包括空指針的所有的節點入隊,若遇到第一個空指針,則後面必然沒有結點,即後面若有節點則必然爲空,否則不是完全二叉樹。
AC代碼
/*
author : eclipse
email : [email protected]
time : Fri Jun 26 19:02:33 2020
*/
#include <bits/stdc++.h>
using namespace std;
struct Node {
int left;
int right;
};
vector<Node> binaryTree;
int root;
int indexValue;
bool levelOrderTraverse() {
queue<int> q;
q.push(root);
while (!q.empty()) {
int front = q.front();
q.pop();
if (front == -1) {
while (!q.empty()) {
if (q.front() != -1) {
indexValue = root;
return false;
}
q.pop();
}
} else {
indexValue = front;
q.push(binaryTree[front].left);
q.push(binaryTree[front].right);
}
}
return true;
}
int main(int argc, char const *argv[]) {
int N;
scanf("%d", &N);
binaryTree.resize(N);
vector<bool> children;
children.resize(N);
for (int i = 0; i < N; i++) {
string left, right;
cin >> left >> right;
if (left == "-") {
binaryTree[i].left = -1;
} else {
int child = atoi(left.c_str());
children[child] = true;
binaryTree[i].left = child;
}
if (right == "-") {
binaryTree[i].right = -1;
} else {
int child = atoi(right.c_str());
children[child] = true;
binaryTree[i].right = child;
}
}
for (int i = 0; i < children.size(); i++) {
if (!children[i]) {
root = i;
break;
}
}
printf("%s ", (levelOrderTraverse() ? "YES" : "NO"));
printf("%d", indexValue);
return 0;
}
樣例輸入1
9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -
樣例輸出1
YES 8
樣例輸入2
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -
樣例輸出2
NO 1
鳴謝
最後
- 由於博主水平有限,不免有疏漏之處,歡迎讀者隨時批評指正,以免造成不必要的誤解!