• P1305 新二叉树


    https://www.luogu.com.cn/problem/P1305

    本题按照自己理解,如果N个字符串是乱序输入的话,需要先找根再从根先序遍历,便有如下代码:

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 int n;
     4 string s;
     5 struct node{
     6     char lch, rch;
     7 };
     8 node t[26];//存放树节点下标对应26个字母为  c-'a'; 
     9 int f[30];//标记父亲,用于查找根节点 
    10 int root;//用于查找根下标 ,本题比较水的原因在于根节点在第一个字符 
    11 void qxbl(int r){//前序遍历 
    12     cout<<char(r+'a');//输出根数据 
    13     if(t[r].lch!='*')
    14         qxbl(t[r].lch-'a');//递归左左子 
    15     if(t[r].rch!='*')
    16         qxbl(t[r].rch-'a');//递归右儿子 
    17 }
    18 int main()
    19 {    
    20     memset(f, -1, sizeof(f)); //初始化所有节点的父亲为-1 
    21     cin>>n;
    22     for(int i=0; i<n; i++){
    23         cin>>s;
    24         //if(i==0)root=s[i]-'a';
    25         t[s[0]-'a'].lch=s[1];
    26         t[s[0]-'a'].rch=s[2];
    27         if(s[1]!='*')//标记父亲节点 
    28             f[s[1]-'a']=s[0]-'a';
    29         if(s[2]!='*')//标记父亲节点 
    30             f[s[2]-'a']=s[0]-'a';
    31     }
    32     for(int i=0; i<26; i++){//找根节点,没有父亲的节点为根节点 
    33         if(f[i]==-1){
    34             root=i;
    35             break;
    36         } 
    37     }
    38     qxbl(root); 
    39     return 0;
    40  } 

    但经过测试,数据很水,第一字符串中第一个字符即为根节点,所以对上述代码删除精简如下:

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 int n;
     4 string s;
     5 struct node{
     6     char lch, rch;
     7 };
     8 node t[26];//存放树节点下标对应26个字母为  c-'a'; 
     9 int root;//用于查找根下标 ,本题比较水的原因在于根节点在第一个字符 
    10 void qxbl(int r){//前序遍历 
    11     cout<<char(r+'a');//输出根数据 
    12     if(t[r].lch!='*')
    13         qxbl(t[r].lch-'a');//递归左左子 
    14     if(t[r].rch!='*')
    15         qxbl(t[r].rch-'a');//递归右儿子 
    16 }
    17 int main()
    18 {    
    19     cin>>n;
    20     for(int i=0; i<n; i++){
    21         cin>>s;
    22         if(i==0)root=s[i]-'a';
    23         t[s[0]-'a'].lch=s[1];
    24         t[s[0]-'a'].rch=s[2];
    25     }
    26 
    27     qxbl(root); 
    28     return 0;
    29  } 
  • 相关阅读:
    format的用法

    TADOQuery池
    10分钟了解JSON Web令牌(JWT)
    PHP操作Redis数据库常用方法
    平时在PHP编码时有没有注意到这些问题
    利用 Composer 一步一步构建自己的 PHP 框架(四)——使用 ORM
    ORM的详解
    oracle NLS_LANG环境变量设置
    验证选择每日学习总结:DropDownList是否已选择验证、存储过程参数为sql字符串问题、将截断字符串或二进制数据。\r\n语句已终止
  • 原文地址:https://www.cnblogs.com/tflsnoi/p/14223213.html
Copyright © 2020-2023  润新知