1. 程式人生 > >10 二叉樹-鏈式存儲-遞歸遍歷

10 二叉樹-鏈式存儲-遞歸遍歷

creat post 復雜度 代碼實現 鏈式存儲 三種遍歷方式 ios 截圖 order

終於進入非線性數據結構的第一站了!

先從簡單的開始回憶起來吧!


1、二叉樹的鏈式存儲

用一個鏈表來存儲一顆二叉樹,每一個結點用鏈表的一個鏈結點來存儲。

通常地,一個二叉鏈表至少包含3個域:數據域data、左指針域lchild、右指針域rchild。

現實應用的過程中,可以按照自己的需求添加其他指針域。

1 typedef struct BitNode{
2 int data;
3 struct BitNode *lchild,*rchild;
4 }BitNode,*BiTree;

2、遍歷

二叉樹的遍歷的定義:

按某個搜索路徑訪問樹中的每個結點,使得每個結點均被訪問一次且僅被訪問一次。

遞歸式訪問二叉樹:

(1)、基本的三種:先序(中左右)、中序(左中右)、後序(左右中)。

(2)、三種遍歷算法的遞歸遍歷左子樹、右子樹的順序都是固定的。只是訪問根節點的順序不同。

(3)、遞歸遍歷中遞歸工作棧恰好為樹的深度,在最壞的情況下,二叉樹是有n個結點而且深度為n的單支樹,此時遍歷算法的空間復雜度為O(n)。

【註】這三種遍歷方式的算法描述簡單易懂,應能作為模板記憶。

3、具體代碼實現

 1 #include<iostream>
 2 #include<stdlib.h>
 3 #include<cstdio>
 4 using namespace
std; 5 #define TRUE 1 6 #define FALSE 0 7 #define OK 1 8 #define ERROR 0 9 #define OVERFLOW -2 10 typedef int Status; 11 typedef int ElemType; 12 13 /*存儲結構描述*/ 14 typedef struct BitNode{ 15 int data; 16 struct BitNode *lchild,*rchild; 17 }BitNode,*BiTree; 18 /*建立樹*/ 19 void initTree(BiTree &T) 20
{ 21 int x; 22 cin>>x; 23 if(x==0) 24 { 25 T=NULL; 26 } 27 else {//按照先序遍歷建樹 28 T=(BitNode*)malloc(sizeof(BitNode)); 29 T->data=x; 30 initTree(T->lchild); 31 initTree(T->rchild); 32 } 33 } 34 35 void visit(BiTree T) 36 { 37 cout<<T->data<< ; 38 } 39 /*遞歸方式訪問樹*/ 40 /*先序遍歷*/ 41 void preOrder(BiTree T) 42 { 43 if(T!=NULL){ 44 visit(T); 45 preOrder(T->lchild); 46 preOrder(T->rchild); 47 } 48 } 49 void inOrder(BiTree T) 50 { 51 if(T!=NULL) 52 { 53 inOrder(T->lchild); 54 visit(T); 55 inOrder(T->rchild); 56 } 57 } 58 void postOrder(BiTree T) 59 { 60 if(T!=NULL) 61 { 62 postOrder(T->lchild); 63 postOrder(T->rchild); 64 visit(T); 65 } 66 } 67 int main() 68 { 69 BiTree tree; 70 cout<<"Create tree in preOrder.:"<<endl; 71 initTree(tree); 72 cout<<"--- show the preorder sequence: ---"<<endl; 73 preOrder(tree); 74 cout<<endl; 75 cout<<"--- show the inorder sequence: ---"<<endl; 76 inOrder(tree); 77 cout<<endl; 78 cout<<"--- show the postorder sequence: ---"<<endl; 79 postOrder(tree); 80 return 0; 81 }

4、實現截圖

技術分享

10 二叉樹-鏈式存儲-遞歸遍歷