zoukankan      html  css  js  c++  java
  • 7-13 是否完全二叉搜索树 (30 分)

    题目链接:https://pintia.cn/problem-sets/1108925599999025152/problems/1108925672111693826

    题目大意:

    将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。

    输入格式:

    输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。

    输出格式:

    将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES,如果该树是完全二叉树;否则输出NO

    具体思路:建树的话,按照题目条件简历就可以了。具体判断是不是完全二叉树的时候,就是给每个点编号,根节点为1,然后子左节点为2,字右节点为3.按照这个编号形式,然后看最后一个节点的编号和n个关系,如果大于n的话,就不是完全二叉树。

    AC代码:

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 # define ll long long
     4 # define inf 0x3f3f3f3f
     5 const int maxn = 2e5+100;
     6 double a[maxn];
     7 struct node
     8 {
     9     node *lt;
    10     node *rt;
    11     int data;
    12     int id;
    13 
    14 };
    15 int flag=0;
    16 int k;
    17 int tt;
    18 node *Insert(node *root,int data)
    19 {
    20     if(root==NULL)
    21     {
    22         tt=1;
    23         root=new node;
    24         root->data=data;
    25         root->lt=NULL;
    26         root->rt=NULL;
    27         return root;
    28     }
    29     else if(root)
    30     {
    31         if(tt==0)
    32         {
    33             if(data>=root->data)root->lt=Insert(root->lt,data);
    34             else root->rt=Insert(root->rt,data);
    35         }
    36     }
    37     return root;
    38 }
    39 int n;
    40 void judge(node*root)
    41 {
    42     queue<node*>q;
    43     q.push(root);
    44     root->id=1;
    45     while(!q.empty())
    46     {
    47         node *top=q.front();
    48         q.pop();
    49         if(top->id>n)flag=1;
    50         if(k==0)cout<<top->data,k=1;
    51         else cout<<" "<<top->data;
    52         if(top->lt){
    53                 q.push(top->lt),top->lt->id=top->id*2;
    54         }
    55         if(top->rt){
    56                 q.push(top->rt),top->rt->id=top->id*2+1;
    57         }
    58     }
    59 }
    60 int main()
    61 {
    62     int tmp;
    63     k=0;
    64     cin>>n;
    65     node *head=NULL;
    66     for(int i=1; i<=n; i++)
    67     {
    68         tt=0;
    69         cin>>tmp;
    70     //    cout<<tmp<<endl;
    71         head=Insert(head,tmp);
    72     }
    73     judge(head);
    74     cout<<endl;
    75     if(!flag)
    76     {
    77         printf("YES
    ");
    78     }
    79     else printf("NO
    ");
    80     return 0;
    81 }
  • 相关阅读:
    提前期分类
    物料属性,MRP/MPS属性
    ASP.NET刷新页面的一些方法
    Nothing 和 Is
    三层架构与MVC
    ADO.NET
    软件工程之数据流程图(DFD Data Flow Diagram)
    VB.NET小结
    推荐开发人员看的具有影响力的书籍
    C++考试
  • 原文地址:https://www.cnblogs.com/letlifestop/p/10583111.html
Copyright © 2011-2022 走看看