二叉樹的結構定義為:
struct BinTree{int data;BinTree* lchild;BinTree* rchild;};
樹深度的遞迴演算法:
//求樹深度的遞迴演算法,根深度為1int Depth(BinTree T){int m,n;if(!T)return 0;else{m=Depth(T->lchild);n=Depth(T->rchild);return (m>n?m:n)+1;}}
二叉樹中以值為x的結點為根的子樹深度:
//求二叉樹中以值為x的結點為根的子樹深度int Get_Sub_Depth(BinTree T, int x){int m,n;if(T){if(T->data==x)return Depth(T);//找到了值為x的結點,求x為根的子樹的其深度else{//在左右子樹中繼續尋找if(T->lchild)m=Get_Sub_Depth(T->lchild,x);if(T->rchild)n=Get_Sub_Depth(T->rchild,x);}return m>n?m:n;}return 0;}
交換所有結點的左右子樹:
//交換所有結點的左右子樹void Bitree_Revolute(BinTree* T){if(T){//交換左右子樹BinTree* temp;temp = (BinTree*)malloc(sizeof(BinTree));temp = T->lchild;T->lchild = T->rchild;T->rchild = temp;if(T->lchild)Bitree_Revolute(T->lchild);if(T->rchild)Bitree_Revolute(T->rchild); }}
根據順序儲存結構建立二叉鏈表:
//根據順序儲存結構建立二叉鏈表int CreateBitree_SqList(BinTree &T,SqList sa){BinTree ptr[sa.last+1]; //該數組儲存與sa中各結點對應的樹指標if(!sa.last){T=NULL; //空樹Return 1;}ptr[1]=(BTNode*)malloc(sizeof(BTNode));ptr[1]->data=sa.elem[1]; //建立樹根T=ptr[1]; T->lchild=T->rchild=NULL;for(i=2;i<=sa.last;i++){if(!sa.elem[i])return 0; //順序錯誤ptr[i]=(BTNode*)malloc(sizeof(BTNode));ptr[i]->data=sa.elem[i];ptr[i]->lchild=ptr[i]->rchild=NULL;j=i/2; //找到結點i的雙親jif(i==j*2) ptr[j]->lchild=ptr[i]; //i是j的左孩子else if(i==2*j+1)ptr[j]->rchild=ptr[i]; //i是j的右孩子}return 1;}