1. 程式人生 > >PAT 1110 Complete Binary Tree[比較]

PAT 1110 Complete Binary Tree[比較]

stdio.h you pos rate view sample 一個 c_str 但是

1110 Complete Binary Tree (25 分)

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

題目大意:給出一個二叉樹,判斷是否是完全二叉樹。

//這個題真的學到了不少東西。我的AC:

參照了:https://blog.csdn.net/hyf20144055065/article/details/51970789

#include <iostream>
#include <algorithm>
#include
<cstdio> #include<stdio.h> #include <queue> #include<cmath> #include <vector> using namespace std; struct Node{ int left=-1,right=-1; }node[20]; int isr[20]; int root=-1; int ct=0,n,last=0; void level(int r){//進行層次遍歷。我是選擇在入隊的時候+,但是這樣是比較復雜的,我應該在出隊的時候+。 queue<int> qu; qu.push(r); //ct++; while(!qu.empty()){ //if(ct==n)last=qu.back(); int top=qu.front();qu.pop(); if(top==-1)break; last=top;//每次last都賦值為當前。 ct++; // if(node[top].left==-1)break; // else { // qu.push(node[top].left); // ct++; // } qu.push(node[top].left);//其實這裏-1完全可以push進去,因為下一次再次彈出時會進行判斷的。 qu.push(node[top].right); // if(node[top].left!=-1){ // qu.push(node[top].right); // ct++; // } } } int main() { cin>>n; string l,r; for(int i=0;i<n;i++){ cin>>l>>r; if(l!="-"){ node[i].left=atoi(l.c_str());//註意這裏的轉換 //cout<<node[i].left<<‘\n‘; isr[node[i].left]=1; } if(r!="-"){ node[i].right=atoi(r.c_str()); isr[node[i].right]=1; } } for(int i=0;i<n;i++){ if(isr[i]==0){ root=i;break; } } level(root); if(ct==n) cout<<"YES "<<last; else cout<<"NO "<<root; return 0; }

1.利用完全二叉樹的性質來判斷。

2。使用了層次遍歷,但是我的層次遍歷思路是不正確的。

3.我的思路:只要有左子節點就push進去,然後計數+1,是在入隊的時候計算數量。只要左子節點為-1,那麽就break掉。

4.正確思路:當節點左右為空-1時,可以push進去,在whlle循環中會進行判斷,如果是-1,那麽就break了,是在出隊的時候進行+1操作,這樣最後就可以了

5.在我原來的那種方法中,2和6測試點過不去,對於6測試點:

使用了

1

- -

測試數據進行了更正

2測試點是對於0的檢測。

正確輸出應該是YES 0

PAT 1110 Complete Binary Tree[比較]