#include <stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef char TElemType; /*假設二叉樹結點的元素型別為字符*/
typedef struct BiTNode
{
TElemType data; /*資料域*/
struct BiTNode *lchild,*rchild; /*左,右孩子指標域*/
}BiTNode, *BiTree; /*二叉鏈表*/
void InitBiTree(BiTree &T)
{
T = NULL;
}
BiTree MakeBiTree(TElemType e, BiTree L, BiTree R)
{//創造一顆二叉樹T,其中根結點的值為e,L和R分別作為左子樹和右子樹
BiTree t;
t=(BiTree)malloc(sizeof(BiTNode));
if (NULL==t) return NULL;
t->data = e;
t->lchild = L;
t->rchild = R;
return t;
}
void DestoryBiTree(BiTree &T)
//初始條件:二叉樹T已存在,操作結果:銷毀二叉樹T。
{
if(T){
DestoryBiTree(T->lchild);
DestoryBiTree(T->rchild);
free(T);
}
}
Status BiTreeEmpty(BiTree T)
//初始條件:二叉樹T已存在。操作結果:對二叉樹判空。若為慷訓傳TRUE,否則回傳FALSE。
{
if(T==NULL) /* 根結點為空,則樹空 */
return TRUE;
else
return FALSE;
}
Status BreakBiTree(BiTree &T,BiTree &L,BiTree &R)
//初始條件:二叉樹T已存在。操作結果:將一棵二叉樹T分解成根,左子樹和右子樹3個部分。
{
if (T)
{
L = T->lchild;
R = T->rchild;
T->lchild = NULL;
T->rchild = NULL;
return OK;
}
else return ERROR;
}
Status RePlaceLeft(BiTree &T,BiTree <)
//初始條件:二叉樹T已存在。操作結果:替換左子樹。若T非空,則用LT替換T的左子樹,并用LT回傳T的原有左子樹。
{ BiTree temp;
if (NULL == T)return ERROR;
temp = T->lchild;
T->lchild = LT;
LT = temp;
return OK;
}
Status RePlaceRight(BiTree &T,BiTree &RT)
//初始條件:二叉樹T已存在。操作結果:替換右子樹。若T非空,則用RT替換T的左子樹,并用RT回傳T的原有右子樹。
{ BiTree temp;
if (NULL == T)return ERROR;
temp = T->rchild;
T->rchild = RT;
RT = temp;
return OK;
}
Status Display(BiTree T)
{ if (T == NULL)
{ printf("#");
return ERROR;
} else
{
printf("%c",T->data);
printf("(");
Display(T->lchild);
printf(",");
Display(T->rchild);
printf(")");
return OK; }
}
int main(void)
{
int i;
TElemType e;
BiTree T, L, R, A, B, C, D, E, F, G;
InitBiTree(T);
e = 'D';
D = MakeBiTree(e, NULL, NULL);
e = 'E';
E = MakeBiTree(e, NULL, NULL);
e = 'B';
B = MakeBiTree(e, D, E);
e = 'F';
F = MakeBiTree(e, NULL, NULL);
e = 'G';
G = MakeBiTree(e, NULL, NULL);
e = 'C';
C = MakeBiTree(e, F, G);
e = 'A';
A = MakeBiTree(e, B, C);
T = A;
printf("T 的序列\n");
Display(T);
printf("\n 判空\n");
i = BiTreeEmpty(T);
if (i)printf("是\n");
else printf("否\n");
printf("\n 執行替換,用 LR 替換 T 左右子樹\n");
RePlaceLeft(T, L);
RePlaceRight(T, R);
printf("T 的序列\n");
Display(T);
printf("\nL 的序列\n");
Display(L);
printf("\nR 的序列\n");
Display(R);
printf("\n 分解操作,左右分到 LR\n");
BreakBiTree(T, L, R);
printf("T 的序列\n");
Display(T);
printf("\nL 的序列\n");
Display(L);
printf("\nR 的序列\n");
Display(R);
printf("\n 銷毀 T\n");
DestoryBiTree(T);
printf("T 的序列\n");
Display(T);
printf("\n 判空\n");
i = BiTreeEmpty(T);
if (i)printf("是\n");
else printf("否\n");
}
uj5u.com熱心網友回復:
看Call Stackuj5u.com熱心網友回復:
L和R的值是隨機的,沒有被初始化過。作為指標就可能亂指,很可能指向本程式之外的記憶體,從而由作業系統的頁面保護引起例外。轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/229585.html
標籤:C++ 語言
