二叉树的存储结构及四种遍历(C语言)
生活随笔
收集整理的這篇文章主要介紹了
二叉树的存储结构及四种遍历(C语言)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
二叉樹的存儲結構:
typedef struct TNode *Position; typedef Position BinTree; /* 二叉樹類型 */ struct TNode{ /* 樹結點定義 */ElementType Data; /* 結點數據 */BinTree Left; /* 指向左子樹 */BinTree Right; /* 指向右子樹 */ };二叉樹的四種遍歷:
void InorderTraversal( BinTree BT ) {if( BT ) {InorderTraversal( BT->Left );/* 此處假設對BT結點的訪問就是打印數據 */printf("%d ", BT->Data); /* 假設數據為整型 */InorderTraversal( BT->Right );} }void PreorderTraversal( BinTree BT ) {if( BT ) {printf("%d ", BT->Data );PreorderTraversal( BT->Left );PreorderTraversal( BT->Right );} }void PostorderTraversal( BinTree BT ) {if( BT ) {PostorderTraversal( BT->Left );PostorderTraversal( BT->Right );printf("%d ", BT->Data);} }void LevelorderTraversal ( BinTree BT ) { Queue Q; BinTree T;if ( !BT ) return; /* 若是空樹則直接返回 */Q = CreatQueue(); /* 創建空隊列Q */AddQ( Q, BT );while ( !IsEmpty(Q) ) {T = DeleteQ( Q );printf("%d ", T->Data); /* 訪問取出隊列的結點 */if ( T->Left ) AddQ( Q, T->Left );if ( T->Right ) AddQ( Q, T->Right );} }總結
以上是生活随笔為你收集整理的二叉树的存储结构及四种遍历(C语言)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络安全专家教你设置史上最安全的WiFi
- 下一篇: 编程中的一种特殊递归-尾递归