zoukankan      html  css  js  c++  java
  • PAT 1110 Complete Binary Tree

    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

    #include<iostream>
    #include<vector>
    #include<string>
    using namespace std;
    vector<int> tree(21,-1), Left(20,-1), Right(20,-1), record(20,0);
    int n;
    void buildtree(int root){ 
        if(Left[tree[root]]!=-1){
        	if(2*root+1>19)
        		return;	
          tree[2*root+1]=Left[tree[root]];
          buildtree(2*root+1);
        }
        if(Right[tree[root]]!=-1){
        	if(2*root+2>19)
            	return;
          tree[2*root+2]=Right[tree[root]];
          buildtree(2*root+2);
        }
    }
    int main(){
      cin>>n;
      string l, r;
      for(int i=0; i<n; i++){
        cin>>l>>r;
        if(l[0]!='-'){
          Left[i]=stoi(l);
          record[Left[i]]=1;
        }
        if(r[0]!='-'){
          Right[i]=stoi(r);
          record[Right[i]]=1;
        }
      }
      int i=0;
      for(; i<n; i++)
         if(record[i]==0)
            break;
      tree[0]=i;
      buildtree(0);
      int cnt=0;
      for(int i=0; i<=20; i++)
      	if(tree[i]==-1)
      	  if(i==n){
      	  		cout<<"YES "<<tree[n-1]<<endl;
      	  		return 0;
    		}
          else{
          		cout<<"NO "<<tree[0]<<endl;
          		return 0; 
    	  } 
    }
    
  • 相关阅读:
    Mac下配置Android adb环境变量
    在远程Linux上搭建jenkins
    早期渲染模板-Thymeleaf总结
    启动SpringBoot时的banner自定义修改
    MySQL密码策略及修改或忘记密码
    (转)Maven使用总结
    转-安全层开发—Shiro对比Spring Security
    JavaWeb应用-发布打成jar包和war包区别
    Gitea中常规git工作流程
    简述JSP与Servlet的区别及联系
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/9501934.html
Copyright © 2011-2022 走看看