zoukankan      html  css  js  c++  java
  • 二叉树的创建,和三种递归遍历方式

    在运行窗口输入:

     A B D # # F E # # # C G # H # # I # #
     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 typedef char ElementType;
     5 typedef struct TNode *Position;
     6 typedef Position BinTree;    //二叉树类型
     7 struct TNode {
     8     ElementType Data;    //结点数据
     9     BinTree Left;        //指向左子树
    10     BinTree Right;        //指向右子树
    11 };
    12 
    13 void printBinTree(BinTree BT, int Depth);
    14 
    15 
    16 BinTree CreateBinaryTree(BinTree BT)
    17 {
    18     char dt;
    19     //printf("please enter a character: ");
    20     scanf_s("%c", &dt);
    21     getchar();
    22     if (dt == '#')
    23         return NULL;
    24     else
    25     {
    26         if (!BT)
    27         BT = (BinTree)malloc(sizeof(struct TNode));
    28         BT->Data = dt;
    29         BT->Left = NULL;
    30         BT->Right = NULL;
    31         //printf("please enter the left son of %c: ", dt);
    32         BT->Left = CreateBinaryTree(BT->Left);
    33         //printf("please enter the right son of %c: ", dt);
    34         BT->Right = CreateBinaryTree(BT->Right);
    35         return BT;
    36     }
    37     
    38 }
    39 
    40 
    41 
    42 void InorderTraversal(BinTree BT, int Depth)
    43 {
    44     if (BT)
    45     {
    46         printBinTree(BT, Depth);
    47         InorderTraversal(BT->Left, Depth + 1);
    48         InorderTraversal(BT->Right, Depth + 1);
    49         
    50         //printf("%c", BT->Data);
    51         
    52     }
    53 }
    54 
    55 void printBinTree(BinTree BT, int Depth)
    56 {
    57     for (int i = 0; i < Depth; i++)
    58         printf("  ");
    59     printf("%c
    ", BT->Data);
    60 }
    61 
    62 int main()
    63 {
    64     BinTree BT = (BinTree)malloc(sizeof(struct TNode));
    65     BT = CreateBinaryTree(BT);
    66     InorderTraversal(BT, 0);
    67 }
  • 相关阅读:
    查看SQL语句执行时间、IO开销
    创建性能监视器(logman)
    IIS连接数
    SQL Server重建索引计划
    删除不存在的网卡
    授予普通域用户远程桌面连接DC/客户端权限
    AD新建用户、组、OU
    常用短语
    Android之APP模块编译
    Web&网络协议
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/9746051.html
Copyright © 2011-2022 走看看