P1305新二叉树

一、题目描述

 

 二、题目分析

  就是一个构建树,在加上前序打印,水题一只。

三、代码实现

复制代码
 1 #include "bits/stdc++.h"
 2 using namespace std;
 3 struct node{
 4     char date;
 5     node *left = NULL;
 6     node *right = NULL;
 7 };
 8 void find(node *root,string ans)
 9 {
10     if(root == NULL)
11         return;
12     if(root->date == ans[0]){
13         root->left = new node();
14         if(ans[1] == '*')
15             root->left = NULL;
16         else 
17             root->left->date = ans[1];
18         root->right = new node();
19         if(ans[2] == '*')
20             root->right = NULL;
21         else 
22             root->right->date = ans[2];
23         return;
24     }
25     find(root->left,ans);
26     find(root->right,ans);
27 }
28 void printPre(node *root)
29 {
30     if(root == NULL)
31         return;
32     cout << root->date;
33     printPre(root->left);
34     printPre(root->right);
35 }
36 int main()
37 {
38     int n;
39     node root;
40     cin >> n;
41     for(int i = 0;i < n;i++){
42         string ans;
43         cin >> ans;
44         if(i == 0){
45             root.date = ans[0];
46             root.left = new node();
47             if(ans[1] == '*')
48                 root.left = NULL;
49             else
50                 root.left->date = ans[1];
51             root.right = new node();
52             if(ans[2] == '*')
53                 root.right = NULL;
54             else    
55                 root.right->date = ans[2];
56         }
57         else 
58             find(&root,ans);
59     }
60     printPre(&root);
61     return 0;
62 }
复制代码

 

posted @   scannerkk  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示