创建排序二叉树:插入时,从根开始遍历。
如果比根小,判断有没有左节点,有则向左走,没有则将该节点作为左节点。
如果比根大,判断有没有右节点,有则向右走,没有则将该节点作为右节点。
初级版代码:
Tree* Create(int * arr,int len) { Tree* pRoot = (Tree*)malloc(sizeof(Tree)); pRoot->val = arr[0]; pRoot->pleft = NULL; pRoot->pright = NULL; for(int i = 1; i < len;i++) { Tree* tree = (Tree*)malloc(sizeof(Tree)); tree->val = arr[i]; tree->pleft = NULL; tree->pright = NULL; Tree* tmp = pRoot; while(1) { if(arr[i] == tmp->val) return NULL; else if(arr[i] < tmp->val) if(tmp->pleft != NULL) tmp = tmp->pleft; else {tmp->pleft = tree; break;} else if(arr[i] > tmp->val) if(tmp->pright != NULL) tmp = tmp->pright; else { tmp->pright = tree; break;} } } return pRoot; }
升级版代码:
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. "); 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; }