创建排序二叉树:插入时,从跟开始遍历。
如果比根小,判断有没有左节点,有则向左走,没有则将该节点作为左节点。
如果比根大,判断有没有右节点,有则向右走,没有则将该节点作为右节点。
void InsertNode(BinaryTree **pTree,int nNum) { BinaryTree *pTemp = NULL; pTemp = (BinaryTree*)malloc(sizeof(BinaryTree)); pTemp->nValue = nNum; pTemp->pLeft = NULL; pTemp->pRight = NULL; //树空 if(*pTree == NULL) { *pTree = pTemp; return; } BinaryTree *pNode = NULL; pNode = *pTree; while(1) { if(pNode->nValue > nNum) { //去左侧 if(pNode->pLeft == NULL) { pNode->pLeft = pTemp; return; } pNode = pNode->pLeft; } else if(pNode->nValue < nNum) { //右侧 if(pNode->pRight == NULL) { pNode->pRight = pTemp; return; } pNode = pNode->pRight; } else { //相等 printf("error.\n"); return; } } } BinaryTree *CreateBST(int arr[],int nLength) { if(arr == NULL || nLength <=0)return NULL; BinaryTree *pTree = NULL; int i; for(i = 0;i<nLength;i++) { InsertNode(&pTree,arr[i]); } return pTree; }