二叉树的创建和文本显示

题目要求:

第一步建立二叉树;

第二步打印; 

打印时应当特别注意是先遍历右子树输出,然后输出根节点,再遍历左子树输出。

源码与注释:

 1 #include <bits/stdc++.h>
 2 #include <string>
 3 
 4 using namespace std;
 5 string s;
 6 
 7 typedef struct Node{
 8     string data;
 9     struct Node* left;
10     struct Node* right;
11 }Node;
12 
13 //建立二叉树
14 void Build(Node* &tree){
15     cin>>s;
16     if(s[0]=='#')   tree=NULL;  //为'#'时节点为空
17     else{
18         tree=new Node;
19         tree->data=s;
20         Build(tree->left);
21         Build(tree->right);
22     }
23 }
24 
25 //打印二叉树
26 void Print_tree(Node* tree,int layer){      
27     if(!tree)   return;         
28     Print_tree(tree->right,layer+1);    //先遍历打印右子树
29     if(layer!=1){
30         for(int i=0;i<(layer-1)*4;i++)      //按格式输出
31             printf(" ");
32     }
33     for(int i=0;i<tree->data.size();i++)
34         printf("%c",tree->data[i]);
35     printf("\n");
36     Print_tree(tree->left,layer+1);     //遍历打印左子树
37 }
38 
39 int main()
40 {
41     while(cin>>s){          //接收字符
42         Node* tree = new Node;
43         tree->data=s;         //建立根节点
44         Build(tree->left);     //建立左子树
45         Build(tree->right);     //建立右子树
46         Print_tree(tree,1);     //遍历输出树
47         printf("\n");
48     }
49     return 0;
50 }

猜你喜欢

转载自www.cnblogs.com/jxxclj/p/9253001.html