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 }
本文来自博客园,作者:{scanner},转载请注明原文链接:{https://home.cnblogs.com/u/scannerkk/}