P1305-新二叉树

 1 #include <bits/stdc++.h>
 2 #define _for(i,a,b) for(int i = (a);i < b;i ++)
 3 typedef long long ll;
 4 using namespace std;
 5 int N;
 6 string s[30];
 7 inline ll read()
 8 {
 9     ll ans = 0;
10     char ch = getchar(), last = ' ';
11     while(!isdigit(ch)) last = ch, ch = getchar();
12     while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
13     if(last == '-') ans = -ans;
14     return ans;
15 }
16 inline void write(ll x)
17 {
18     if(x < 0) x = -x, putchar('-');
19     if(x >= 10) write(x / 10);
20     putchar(x % 10 + '0');
21 }
22 struct TreeNode
23 {
24     char val;
25     TreeNode *left;
26     TreeNode *right;
27 };
28 int go(char c)
29 {
30     _for(i,0,N)
31         if(s[i][0]==c)
32             return i;
33     return -1;
34 }
35 TreeNode* build(int cur,char give)
36 {
37     if(give=='*')
38         return NULL;
39     TreeNode* t = (TreeNode*)malloc(sizeof(TreeNode));
40     t->val = give;
41     t->left = build(go(s[cur][1]),s[cur][1]);
42     t->right = build(go(s[cur][2]),s[cur][2]);
43     return t;
44 }
45 void preorder(TreeNode *root)
46 {
47     if(!root)
48         return ;
49     printf("%c",root->val);
50     preorder(root->left);
51     preorder(root->right);
52 }
53 int main()
54 {
55     TreeNode* root;
56     N = read();
57     _for(i,0,N)
58         cin >> s[i];
59     root = build(0,s[0][0]);
60     preorder(root);
61     return 0;
62 }

 

posted @ 2019-08-02 11:43  Asurudo  阅读(175)  评论(0编辑  收藏  举报