洛谷——P1305 新二叉树(新建二叉树以及遍历)


题目描述
输入一串二叉树,用遍历前序打出。

输入输出格式
输入格式:

第一行为二叉树的节点数n。(n leq 26n≤26)

后面n行,每一个字母为节点,后两个字母分别为其左右儿子。

空节点用*表示

输出格式:

前序排列的二叉树

输入输出样例
输入样例#1: 复制
6
abc
bdi
cj*
d**
i**
j**
输出样例#1: 复制
abdicj

#include<bits/stdc++.h>
using namespace std;


struct Node{
    char lch = '*';//左孩子 默认为* 表示没有
    char rch = '*';//右边的孩子 
}; 
bool vis[26];//判断有没有出现过 遍历的时候直接用了
bool isNotRoot[26];//判断是不是根如果出现了还是false那么就根
Node tree[29];//

void build(char root,char left,char right){
    vis[root-'a']=true;
    if(left !='*'){
        tree[root-'a'].lch = left; 
        isNotRoot[left-'a'] = true;//肯定不是根了 
        vis[left-'a'] = true;
    } 
    if(right !='*'){
        tree[root-'a'].rch = right;
        isNotRoot[right-'a'] = true;//肯定不是根了 
        vis[right-'a'] = true;//出现过了 
    }
}
void pre(char root){//前序遍历 
    if(root=='*'){
        return;//如果是空的直接返回 
    }
    printf("%c",root);
    pre(tree[root-'a'].lch);
    pre(tree[root-'a'].rch);
     
} 
int main(){
    int n = 0;
    scanf("%d",&n);
    for(int i = 0;i < n;i++){
    
        char num[4];
        scanf("%s",num);
        build(num[0],num[1],num[2]);//变成一二叉树了 
    
    } 
    
    for(int i = 0;i<26;i++){//找到树根 
        if(vis[i]==true && isNotRoot[i]==false){
            pre(i+'a');
            break;        
        }
    }    
    printf("
");
    
    return 0;
}
原文地址:https://www.cnblogs.com/xiaonuolen/p/10284598.html