Given a tree, you are supposed to tell if it is a complete binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤20) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a -
will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each case, print in one line YES
and the index of the last node if the tree is a complete binary tree, or NO
and the index of the root if not. There must be exactly one space separating the word and the number.
Sample Input 1:
9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -
Sample Output 1:
YES 8
Sample Input 2:
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -
Sample Output 2:
NO 1
解題思路
給定若干的二叉樹,問是夠能夠組成一顆完全二叉樹, 是的話輸出完全二叉樹中最後一個元素, 如果不是輸出根節點。 符合是完全二叉樹的條件是從根節點遍歷,到最後元素的下標值等於節點個數值。
輸入方式: 行數代表根節點,行數輸出的值爲根節點元素,如果如果爲空,用-
帶替。
過程:
- 找到根節點,二叉樹的性質中根節點不會作爲子節點, 圖示中的根節點就是6,通過hash的方法找到根節點。
- 遍歷選擇dfs,這樣方便找對應節點的下標。
- 判斷是否是完全二叉樹, 如果是完全二叉樹的話節點個數和最後一個節點的下標數相同,如果不是的話,那麼最後一個節點的下標數 > 節點數, 因爲其中存在不連續的下標值,所以最後一個節點的下標數一定比節點個數的值大。
圖示
給定的起始的二叉樹如下:
完成構建二叉樹:
解題代碼
#include <iostream>
using namespace std;
int btree[25][2], a[25];
int n, idx, last;
void dfs(int v, int cur){
if (v == -1) return;
if (idx < cur) idx = cur, last = v;
dfs(btree[v][0], 2 * cur);
dfs(btree[v][1], 2 * cur + 1);
}
int main(){
scanf("%d", &n);
for(int i = 0; i < n; i++){
string sl, sr;
cin >> sl >> sr;
btree[i][0] = btree[i][1] = -1;
if (sl != "-") btree[i][0] = stoi(sl), a[stoi(sl)] = 1;
if (sr != "-") btree[i][1] = stoi(sr), a[stoi(sr)] = 1;
}
int root;
for (int i = 0; i < n; i++) if (!a[i]) root = i;
dfs(root, 1);
if (idx == n) printf("YES %d", last);
else printf("NO %d", root);
return 0;
}