二叉树的建立与三种遍历

树是一种数据结构,为什么叫它“树”,因为它倒过来就是一棵树

根在上,而叶在下

其概念主要有根、父、子、深、叶等,

如上图:A为这棵树的根

    B为D的父,而D则为B的子

    E、F、G互为兄弟,

    D也可以叫叶

    这也是一棵深度为2的数 ps:A节点为深度0

所谓的N叉树即它每个(父)节点下有N个(子)节点

= =一般常用的树为二叉树,我就先试着学习学习了

下面代码:

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 
 5 typedef struct node{
 6     node *left;
 7     node *right;
 8     char date;
 9     //node(){left=right=NULL;}
10     //node(char &val){date=val,left=right=NULL;}//俩构造函数
11 }Bitnode,*tree;//- -这里还是有点没弄懂,貌似是弄了个指针可以指向自己
12 
13 void createBitree(tree &T)//创建二叉树,应该可以改成循环,不带输入的那种
14 {
15     char c;
16     cin>>c;
17     if(c=='#')
18         T=NULL;
19     else
20     {
21         T=new node;
22         T->date=c;
23         createBitree(T->left);
24         createBitree(T->right);
25     }
26 }
27 void PreTree(tree &T)//先序遍历
28 {
29     if(T)
30     {
31         printf("%c
",T->date);
32         PreTree(T->left);
33         PreTree(T->right);
34     }
35 }
36 
37 void InTree(tree &T)//中序遍历
38 {
39     if(T)
40     {
41         InTree(T->left);
42         printf("%c
",T->date);
43         InTree(T->right);
44     }
45 }
46 
47 void postTree(tree &T)//后序遍历
48 {
49     if(T)
50     {
51         postTree(T->left);
52         postTree(T->right);
53         printf("%c
",T->date);
54     }
55 }
56 
57 
58 int main()
59 {
60     tree T;
61     createBitree(T);
62     //InTree(T);
63     PreTree(T);
64     return 0;
65 }

关于createtree()函数吧,当你输入的叶的值均为'#'即停止输入,一开始我还以为这玩意无限输入……嗯,还得好好消化消化

以上为我本次关于树的学习

          2016.4.18

原文地址:https://www.cnblogs.com/byzsxloli/p/5405475.html