1. 程式人生 > >創建排序二叉樹

創建排序二叉樹

null while bit 排序 pre ron else for 相等

全部代碼

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <assert.h>
  4 
  5 typedef struct node
  6 {
  7     int nValue;
  8     struct node *pLeft;
  9     struct node *pRight;
 10 }BiTree;
 11 
 12 void Add(BiTree **ppRoot, int nNum)
 13 {
 14     BiTree *pTemp = NULL;
15 BiTree *pNode = NULL; 16 17 assert(ppRoot!=NULL); 18 19 //臨時節點開辟空間 20 pTemp = (BiTree *)malloc(sizeof(BiTree)); 21 if(NULL == pTemp) 22 { 23 printf("pTemp空間分配失敗!\n"); 24 exit(-1); 25 } 26 pTemp->nValue = nNum; 27 pTemp->pLeft = NULL;
28 pTemp->pRight = NULL; 29 30 //空樹 31 if(NULL == *ppRoot) 32 { 33 *ppRoot = pTemp; 34 return; 35 } 36 37 pNode = *ppRoot; 38 39 //非空樹 40 while(pNode != NULL) 41 { 42 //比根大 43 if(nNum > pNode->nValue) 44 {
45 //向右走 46 if(NULL == pNode->pRight) 47 { 48 pNode->pRight = pTemp; 49 return; 50 } 51 else 52 { 53 pNode = pNode->pRight; 54 } 55 } 56 //比根小 57 else if(nNum < pNode->nValue) 58 { 59 //向左走 60 if(NULL == pNode->pLeft) 61 { 62 pNode->pLeft = pTemp; 63 return; 64 } 65 else 66 { 67 pNode = pNode->pLeft; 68 } 69 } 70 //相等 出錯 71 else 72 { 73 //釋放臨時節點空間 74 free(pTemp); 75 pTemp = NULL; 76 return; 77 } 78 } 79 } 80 81 BiTree *CreateSBT(int arr[], int len) 82 { 83 BiTree *pRoot = NULL; 84 int i; 85 86 assert(arr!=NULL && len>0); 87 88 for(i=0; i<len; ++i) 89 { 90 Add(&pRoot, arr[i]); 91 } 92 93 return pRoot; 94 } 95 96 void BiTreeTraversal(BiTree *pRoot) 97 { 98 if(NULL == pRoot) 99 { 100 return; 101 } 102 printf("%d ", pRoot->nValue); 103 BiTreeTraversal(pRoot->pLeft); 104 BiTreeTraversal(pRoot->pRight); 105 } 106 107 int main(void) 108 { 109 int arr[] = {1, 7, 3, 4, 5, 6, 7}; 110 int len = sizeof(arr)/sizeof(arr[0]); 111 BiTree *pRoot = CreateSBT(arr, len); 112 BiTreeTraversal(pRoot); 113 114 return 0; 115 }

創建排序二叉樹