1. 程式人生 > >PTA 6-12 (二叉樹的遞歸刪除)

PTA 6-12 (二叉樹的遞歸刪除)

type found == let turn posit malloc tty pre

 1 BinTree Insert( BinTree BST, ElementType X )
 2 {
 3     if (BST==NULL) {
 4         BinTree tmp=(BinTree)malloc(sizeof(struct TNode));
 5         tmp->Data=X;
 6         tmp->Left=tmp->Right=NULL;
 7         return tmp;
 8     };
 9     if (X<BST->Data)  
10         BST->Left=Insert(BST->Left,X);
11 else 12 BST->Right=Insert(BST->Right,X); 13 return BST; 14 } 15 16 Position Find( BinTree BST, ElementType X ) { 17 if (BST==NULL||BST->Data==X) return BST; 18 if (X<BST->Data) return Find (BST->Left,X); 19 else return
Find (BST->Right,X); 20 } 21 22 Position FindMin( BinTree BST ) { 23 if (BST==NULL||BST->Left==NULL) return BST; 24 else return FindMin (BST->Left); 25 } 26 27 Position FindMax( BinTree BST ) { 28 if (BST==NULL||BST->Right==NULL) return BST;
29 else return FindMax (BST->Right); 30 } 31 32 BinTree Delete( BinTree BST, ElementType X ) { 33 BinTree TMP; 34 if (BST==NULL) { 35 printf ("Not Found\n"); 36 return NULL; 37 } 38 if (X<BST->Data) 39 BST->Left=Delete (BST->Left,X); 40 else if (X>BST->Data) 41 BST->Right=Delete (BST->Right,X); 42 else { 43 if (BST->Left!=NULL&&BST->Right!=NULL) { 44 TMP=FindMin (BST->Right); 45 BST->Data=TMP->Data; 46 BST->Right=Delete (BST->Right,TMP->Data); 47 } 48 else { 49 TMP=BST; 50 if (BST->Left!=NULL) 51 BST=BST->Left; 52 else if (BST->Right!=NULL) 53 BST=BST->Right; 54 else BST=NULL; 55 } 56 } 57 return BST; 58 }

PTA 6-12 (二叉樹的遞歸刪除)