二叉樹的儲存:
順序儲存浪費空間。
二叉樹鏈式儲存結構:
typedef int datatype;
typedef struct node{
datatype data;
struct node *lchild,*rchild;
}bitree,*root;
二叉樹的遍曆,由於二叉樹的遞迴性質,遍曆演算法也是遞迴的。三種基本的遍曆演算法如下:
先訪問樹根,再訪問左子樹,最後訪問右子樹 先根遍曆
先訪問左子樹,再訪問樹根,最後訪問右子樹 中根遍曆
先訪問左子樹,再訪問右子樹,最後訪問樹根 後根遍曆。
/*********************二叉樹***********************/#include <stdio.h>#include <stdlib.h>#define N 16typedef struct _node_{ int no; struct _node_ *lchild, *rchild;}bitree;typedef bitree * datatype;typedef struct { datatype data[N]; int front, rear;}sequeue;sequeue *CreateEmptySequeue(){ sequeue *sq; sq = (sequeue*)malloc(sizeof(sequeue)); sq->front = sq->rear = 0; return sq;}int EmptySequeue(sequeue *sq){ return sq->front == sq->rear;}void EnSequeue(sequeue *sq, datatype x){ sq->rear = (sq->rear + 1) % N; sq->data[sq->rear] = x; return;}datatype DeSequeue(sequeue *sq){ sq->front = (sq->front + 1)%N; return sq->data[sq->front];}bitree *CreateBitree(int i, int n){ bitree *root; root = (bitree *)malloc(sizeof(bitree)); root->no = i; if(2*i <= n) root->lchild = CreateBitree(2*i, n); else root->lchild = NULL; if(2*i+1 <= n) root->rchild = CreateBitree(2*i+1, n); else root->rchild = NULL; return root;}/***********遍曆*************/void PreOrder(bitree *root){ if(root == NULL) return; printf("%d ", root->no); PreOrder(root->lchild); PreOrder(root->rchild); return;}void InOrder(bitree *root){ if(root == NULL) return; InOrder(root->lchild); printf("%d ", root->no); InOrder(root->rchild); return;}void PostOrder(bitree *root){ if(root == NULL) return; PostOrder(root->lchild); PostOrder(root->rchild); printf("%d ", root->no); return;}/***********按層次遍曆**************/void NoOrder(bitree *root){ sequeue *sq; sq = CreateEmptySequeue(); EnSequeue(sq, root); while(!EmptySequeue(sq)) { root = DeSequeue(sq); printf("%d ", root->no); if(root->lchild != NULL) EnSequeue(sq, root->lchild); if(root->rchild != NULL) EnSequeue(sq, root->rchild); } return;}int main(){ bitree *root; root = CreateBitree(1, 10); printf(" PreOrder:"); PreOrder(root); printf("\n"); printf(" InOrder:"); InOrder(root); printf("\n"); printf("PostOrder:"); PostOrder(root); printf("\n"); printf(" NoOrder:"); NoOrder(root); printf("\n"); return 0;}