[二叉树建树&完全二叉树判断] 1110. Complete Binary Tree (25)
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 8Sample Input 2:
8 - - 4 5 0 6 - - 2 3 - 7 - - - -Sample Output 2:
NO 1
分析:这道题目的建树与以前的通过中序和前序或者中序和后序建树不同,这里给出了每个孩子的左右孩子,根据这些信息来建树。做法是申明一个节点数组,将对应的节点信息填入数组即可,而左右孩子指针就是数组的下标。另外,关于完全二叉树的判断,网上也有很多资料。
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <vector> #include <queue> using namespace std; struct Node { int data; int lchild,rchild; }node[10000]; int inDreeg[10000]={0}; bool judge(int root,int & last_node) { if(root==-1) return true; queue<int> q; q.push(root); int flag=0; int now; while(!q.empty()) { now=q.front(); q.pop(); //cout<<node[now].data<<endl; if(flag==0) { if(node[now].lchild!=-1&&node[now].rchild!=-1) flag=0; else if(node[now].lchild==-1&&node[now].rchild!=-1) return false; else flag=1; } else { if(node[now].lchild!=-1||node[now].rchild!=-1) return false; } if(node[now].lchild!=-1) q.push(node[now].lchild); if(node[now].rchild!=-1) q.push(node[now].rchild); } last_node=node[now].data; return true; } int main() { int n; scanf("%d",&n); for(int i=0;i<n;i++) { string l,r; cin>>l>>r; node[i].data=i; if(l=="-") { node[i].lchild=-1; } else { int id=atoi(&l[0]); node[i].lchild=id; inDreeg[id]+=1; } if(r=="-") { node[i].rchild=-1; } else { int id=atoi(&r[0]); node[i].rchild=id; inDreeg[id]+=1; } } bool ans; int root=-1; for(int i=0;i<n;i++) { if(inDreeg[i]==0) { root=i; break; } } int last; ans=judge(root,last); if(ans==true) { printf("YES %d\n",last); } else { printf("NO %d\n",root); } }