1. 程式人生 > >1110 Complete Binary Tree (25 分)【完全二叉樹(dfs)】

1110 Complete Binary Tree (25 分)【完全二叉樹(dfs)】

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

題意:有n個點,有n行輸入,從0到n,表示每個點的左右子節點,如果是“-”表示沒有左結點或者右結點,如果是完全二叉樹,就輸出最後的節點的值,如果不是完全二叉樹,就輸出根節點

 解題思路:根據完全二叉樹的性質,我們知道最後一個節點下標跟節點個數相同(下標從1開始),所以我們對二叉樹遍歷,如果最後一個下標等於節點個數就是完全二叉樹,如果是棵二叉樹,那麼最後一個節點的下標會大於節點個數(同樣的結點數,但是前面有位置是空的話)我們根據這個性質來解這題。用結構體儲存點的左右孩子,如果沒有就賦值-1,並且對每個左右節點在Exit賦值為true,表示它是子節點(為了確定根節點,根節點不是孩子節點,所以根節點在Exit中肯定是false),我們對輸入資料處理完,接下來就開始判斷了,通過dfs,對左右子樹遞迴,一旦index大於maxn,就將maxn更新,ans(答案)更新當前根節點,就一直這樣子遞迴。

#include<iostream>
#include<cstdio>
#include<string>
using namespace std;

struct Binary{
	int l,r;
}; 
Binary tree[100];
bool Exit[100]={false};
int maxn=-1,ans;
void dfs(int root,int index){
	if(index>maxn)
	{
		maxn=index;
		ans=root;
	}
	if(tree[root].l!=-1) dfs(tree[root].l,2*index);
	if(tree[root].r!=-1) dfs(tree[root].r,2*index+1); 
}
int main(void)
{
	int n,root=0,index=1;
	scanf("%d",&n);
	
	for(int i=0;i<n;i++)
	{
		string l,r;
		cin>>l>>r;
		if(l=="-") tree[i].l=-1;
		else{
			tree[i].l=stoi(l);
			Exit[tree[i].l]=true;
		} 
		if(r=="-") tree[i].r=-1;
		else {
			tree[i].r=stoi(r);
			Exit[tree[i].r]=true;
		}
	}
	while(Exit[root]!=false) root++;
	dfs(root,index);
//	cout<<maxn<<endl;
	if(maxn==n)
	printf("%s %d\n","YES",ans);
	else
	printf("%s %d\n","NO",root);
	return 0;
}