[二叉樹建樹&徹底二叉樹判斷] 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.node

Input Specification:ios

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:spa

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

分析:這道題目的建樹與之前的經過中序和前序或者中序和後序建樹不一樣,這裏給出了每一個孩子的左右孩子,根據這些信息來建樹。作法是申明一個節點數組,將對應的節點信息填入數組便可,而左右孩子指針就是數組的下標。另外,關於徹底二叉樹的判斷,網上也有不少資料。code

 

#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);
    }
}
相關文章
相關標籤/搜索