zoukankan      html  css  js  c++  java
  • 二叉树的创建和文本显示

    题目要求:(点击图片查看)

    第一步建立二叉树;

    第二步打印; 

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

    源码与注释:

    #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;
    }
  • 相关阅读:
    数据库练习
    pymysql
    数据库索引
    数据库查询
    数据库操作
    数据库建表
    数据库初识
    shell 编程
    Struts2与SpringMVC
    SpringAOP
  • 原文地址:https://www.cnblogs.com/jxxclj/p/9253001.html
Copyright © 2011-2022 走看看