zoukankan      html  css  js  c++  java
  • 数据结构--二叉树

    树是一种重要的非线性数据结构,在计算机科学中有着十分广泛的应用,具有层次性和分支性,我这次仅仅介绍一些二叉树的性质和写法

    二叉树是树的特殊一种,具有如下特点:1、每个结点最多有两颗子树,结点的度最大为2。2、左子树和右子树是有顺序的,次序不能颠倒。3、即使某结点只有一个子树,也要区分左右子树。

    /*
        Name:
        Copyright:
        Author:  流照君
        Date: 2019/8/13 14:42:02
        Description:
    */
    #include <iostream>
    #include<string>
    #include <algorithm>
    #include <vector>
    #define inf 0x3f3f3f3f
    #define child chlid
    using namespace std;
    typedef long long ll;
    typedef char type;
    string s;
    int i=0;
    typedef struct node{  //树节点 
        type ch;
        struct node *lchlid;
        struct node *rchlid;
        node(type c):ch(c),lchlid(NULL),rchlid(NULL){  //构造函数 
        }
    }binary;
    //按先后次序输入二叉树中结点的值(一个字符),#表示空树
    node* creat_tree()  //按先序建树 ,也可以按中或后序建树 
    {
        type cha=s[i++] ;
        if(cha=='#')
        return NULL;
        node* h=new node(cha); //c可以用malloc 
        h->lchlid =creat_tree();
        h->rchlid =creat_tree();
        return h;
    }
    void preorder(binary *h) //前序遍历 递归实现 
    {
        if(h==NULL)
        return ;
        cout<<h->ch ;
        preorder(h->lchlid);
        preorder(h->rchlid);
    }
    void inorder(binary *h)  // 中序遍历 
    {
        if(h==NULL)
        return ;
        inorder(h->lchlid);
        cout<<h->ch;
        inorder(h->rchlid);
    }
    void postorder(binary *h)  // 后序遍历 
    {
        if(h==NULL)
        return ;
        inorder(h->lchlid);
        inorder(h->rchlid);
        cout<<h->ch;
    }
    int get_height(node *h) //得到树的高度 
    {
        if(h==NULL)
        return 0;
        int height=0;
        int hl=get_height(h->lchlid);
        int hr=get_height(h->rchlid);
        height=max(hl,hr)+1;
        return height;
    }
    int main(int argc, char** argv)
    {
        //freopen("in.txt", "r", stdin);
        //freopen("out.txt", "w", stdout);
        cin>>s;
        node *h=creat_tree();
        preorder(h);
        cout<<endl; 
        inorder(h);
        cout<<endl;
        postorder(h);
        cout<<endl;
        cout<<get_height(h)<<endl;
        return 0;
    }
  • 相关阅读:
    .net破解二(修改dll)
    CLR 的执行模型(2)
    理解数据库的几种键和几个范式
    事务隔离级别如何影响锁
    c#和java中封装字段的不同
    Linux安装AUTOCONF和AUTOMAKE产生的程序的一般步骤
    html锚点使用示例
    webbrowser控件使用时的注意事项
    C#实现单实例运行
    为Exchange 2007 SCC 启用 SCR 副本-供需要的人使用!
  • 原文地址:https://www.cnblogs.com/liuzhaojun/p/11346195.html
Copyright © 2011-2022 走看看