题目要求:(点击图片查看)
第一步建立二叉树;
第二步打印;
打印时应当特别注意是先遍历右子树输出,然后输出根节点,再遍历左子树输出。
源码与注释:
#include <bits/stdc++.h> #include <string> using namespace std; string s; typedef struct Node{ string data; struct Node* left; struct Node* right; }Node; //建立二叉树 void Build(Node* &tree){ cin>>s; if(s[0]=='#') tree=NULL; //为'#'时节点为空 else{ tree=new Node; tree->data=s; Build(tree->left); Build(tree->right); } } //打印二叉树 void Print_tree(Node* tree,int layer){ if(!tree) return; Print_tree(tree->right,layer+1); //先遍历打印右子树 if(layer!=1){ for(int i=0;i<(layer-1)*4;i++) //按格式输出 printf(" "); } for(int i=0;i<tree->data.size();i++) printf("%c",tree->data[i]); printf(" "); Print_tree(tree->left,layer+1); //遍历打印左子树 } int main() { while(cin>>s){ //接收字符 Node* tree = new Node; tree->data=s; //建立根节点 Build(tree->left); //建立左子树 Build(tree->right); //建立右子树 Print_tree(tree,1); //遍历输出树 printf(" "); } return 0; }