• 5)二叉树[1]二叉树的遍历(先序、中序、后序)


     1 #include "iostream"
     2 using namespace std;
     3 
     4 typedef char type;
     5 struct bnode{
     6     type data;
     7     bnode *lchild,*rchild;
     8 };
     9 
    10 class tree{
    11 public:
    12     tree();//初始化
    13     ~tree();
    14     void create_tree(bnode *&T);//建立二叉树
    15     void preorder(bnode *T);//先序遍历
    16     void inorder(bnode *T);//中序遍历
    17     void postorder(bnode *T);//后序遍历
    18 private:
    19     int count;//元素个数统计
    20 };
    21 
    22 tree::tree()//初始化
    23 {
    24     count = 0;
    25 }
    26 
    27 void tree::create_tree(bnode *&T)//建立二叉树
    28 {
    29     type x;
    30     cin>>x;
    31     if(x=='.')T=NULL;
    32     else {
    33         T = new bnode;
    34         T->data = x;
    35         count++;
    36         create_tree(T->lchild);
    37         create_tree(T->rchild);
    38     }
    39 }
    40 
    41 void tree::preorder(bnode*T)//先序遍历
    42 {
    43     if(T!=NULL)
    44     {
    45         cout<<T->data<<" ";
    46         preorder(T->lchild);
    47         preorder(T->rchild);
    48     }
    49 }
    50 
    51 void tree::inorder(bnode*T)//中序遍历
    52 {
    53     if(T!=NULL)
    54     {
    55         inorder(T->lchild);
    56         cout<<T->data<<" ";
    57         inorder(T->rchild);
    58     }
    59 }
    60 
    61 void tree::postorder(bnode*T)//后序遍历
    62 {
    63     if(T!=NULL)
    64     {
    65         postorder(T->lchild);
    66         postorder(T->rchild);
    67         cout<<T->data<<" ";
    68     }
    69 }
    70 
    71 tree::~tree(){}
    72 
    73 int main()
    74 {
    75     tree Tree;
    76     bnode *T;
    77     cout<<"Create Tree:";
    78     Tree.create_tree(T);
    79     cout<<"Tree finished!"<<endl;
    80     cout<<"preorder Tree:";
    81     Tree.preorder(T);
    82     cout<<endl;
    83     cout<<"inorder Tree:";
    84     Tree.inorder(T);
    85     cout<<endl;
    86     cout<<"postorder Tree:";
    87     Tree.postorder(T);
    88     cout<<endl;
    89     return 0;
    90 }

  • 相关阅读:
    ZOJ 3769 Diablo III(分组背包)
    HDU 1712 ACboy needs your help(分组背包入门题)
    POJ 1170 Shopping Offers(完全背包+哈希)
    HDU 4489 The King’s Ups and Downs
    [转] LINUX 三种网络连接模式
    [转] 软件架构
    [转] 支付宝系统架构内部剖析
    [转] pip镜像升级报警 -trust-host问题解决方案
    [转] Linux 查找文件内容
    [转] CentOS系统目录学习
  • 原文地址:https://www.cnblogs.com/minmsy/p/5026594.html
Copyright © 2020-2023  润新知