• 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 }

  • 相关阅读:
    VC字符串输出对齐问题(转)
    木马免杀全攻略(转)
    Windows Vista自动重启问题解决方法(转)
    图说VSS 6.0构架版本控制系统解决方案(转)
    几个有用的链接
    X64 Windows 2003 及XP 语言包官方下载
    .NET 3.5的版本问题(转)
    设计模式读书笔记工厂方法模式
    设计模式读书笔记装饰者模式
    设计模式读书笔记简单工厂模式
  • 原文地址:https://www.cnblogs.com/minmsy/p/5026594.html
Copyright © 2020-2023  润新知