你好,我不知道我的BST插入方法有什麼問題。 任何建議它也是非遞歸它增加了正確的總是我想知道爲什麼它增加到BST結束時,當我打印它顯示節點只在右側添加。非遞歸BST(二叉搜索樹)
void InsertBST(LZWCmp cmp, TreeNode **root, int code)
{
TreeNode tmp = *root;
TreeNode current = NULL;
Code temp;
Code temp1;
int size;
int comp;
int direction = -1;
if(*root == NULL)
root = CreateNode(code)
while(tmp != NULL) {
temp = GetCode(cmp->cst, tmp->cNum);
temp1 = GetCode(cmp->cst, code);
size = temp.size;
if(temp1.size < temp.size)
size = temp1.size;
comp = memcmp(temp1.data, temp.data, size);
if(temp1.size < temp.size && comp == 0)
comp = -1;
else if(temp1.size < temp.size && comp == 0)
comp = 1;
if(comp < 0) {
current = tmp;
direction = FALSE;
tmp = tmp->left;
} else (
current = tmp;
direction = TRUE;
tmp = tmp->right;
}
}
if(direction == FALSE)
current->left = CreateNode(code);
else
current->right = CreateNode(code);
}
'根= CreateNode(代碼)'也許應該是'*根= CreateNode(代碼);'(注意分號)另外:刪除變量tmp,並用* root替換它的所有出現。 – wildplasser
是的,但它仍然有相同的問題 – user2822413