码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的创建,和三种递归遍历方式

时间:2018-10-05 22:41:48      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:++   span   amp   运行   lease   sizeof   return   tree   turn   

在运行窗口输入:

 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\n", 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 }

 

二叉树的创建,和三种递归遍历方式

标签:++   span   amp   运行   lease   sizeof   return   tree   turn   

原文地址:https://www.cnblogs.com/hi3254014978/p/9746051.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!