二叉树的建立与三种遍历
生活随笔
收集整理的這篇文章主要介紹了
二叉树的建立与三种遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
樹是一種數據結構,為什么叫它“樹”,因為它倒過來就是一棵樹
根在上,而葉在下
?
其概念主要有根、父、子、深、葉等,
如上圖: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\n",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\n",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\n",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
總結
以上是生活随笔為你收集整理的二叉树的建立与三种遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到和尚吃肉预示什么
- 下一篇: cisco 交换机通过console 导