zoukankan      html  css  js  c++  java
  • 简单二叉树的建立和遍历

    #include<stdio.h>
    #include<stdlib.h>
    
    //定义节点
    typedef struct BiNode{
            char data;
            struct BiNode *lch;
            struct BiNode *rch;
    }BiNode,*BiTree;
    
    //先序建立二叉树
    void Create(BiTree &T)
    {
            T =(BiNode*) malloc (sizeof(BiNode));
    
            printf("Enter the data 
    ");
            scanf(" %c",&T->data);
            if(T->data=='#') T = NULL;
            if(T){
                    Create(T->lch);
                    Create(T->rch);
            }
    }
    
    //先序遍历
    void Preorder (BiTree T)
    {
       if (T) {
          printf(" %c",T->data);   // 访问根结点
    
          Preorder(T->lch); // 遍历左子树
          Preorder(T->rch);// 遍历右子树
       }
    }
    
    //中序遍历
    void Inorder (BiTree T)
    {
         if(T) {
           Inorder(T->lch);
    
           printf(" %c",T->data);
    
           Inorder(T->rch);
           }
    }
    
    //后序遍历
    void Postorder (BiTree T)
    {
         if(T) {
           Postorder(T->lch);
           Postorder(T->rch);
    
           printf(" %c",T->data);
         }
    }
    
    //求二叉树深度
    int TreeDepth(BiTree T)
    {
        int left=0;
        int right=0;
        if(T)
        {
            left=1+Treedepth(T->lch);
            right=1+Treedepth(T->rch);
            return left>right?left:right;
        }
        return 0;
    }
    
    int main()
    {
        //先序建立二叉树
        printf("The fuction Create() is called.
    ");
        BiTree T;
        Create(T);
    
        //三种遍历递归算法
        printf("
    ");
        printf("先序遍历二叉树.
    ");
        Preorder(T);
    
        printf("
    ");
        printf("中序遍历二叉树.
    ");
        Inorder(T);
    
        printf("
    ");
        printf("后序遍历二叉树
    ");
        Postorder(T);
        
        printf("二叉树深度:%d
    ",TreeDepth(T));
        printf("
    ");
        return 0;
    
    }


    测试数据依次输入1,2,4,#,#,5,#,#,3,#,#(无,)
    先序遍历输出:1,2,4,5,3
    中序遍历输出:4,2,5,1,3
    后序遍历输出:4,5,2,3,1
    二叉树深度:3

    原链接:https://www.oschina.net/code/snippet_103214_1381

  • 相关阅读:
    print 带颜色打印
    bootstrap-duallistbox使用
    Linux 查看和更改系统字符集
    nginx 不重装实现动态添加模块
    ubuntu 安装openssh-server出现依赖关系解决
    linux安装和使用zookeeper
    网页背景蜘蛛丝特效
    RabbitMQ与SpringBoot整合
    Redis常用命令
    设计模式(Design Patterns)
  • 原文地址:https://www.cnblogs.com/liesun/p/7350335.html
Copyright © 2011-2022 走看看