您好我不知道我的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);
}
答案 0 :(得分:0)
你去了:
void InsertBST(LZWCmp cmp, TreeNode **root, int code)
{
Code temp;
Code temp1;
int size;
int comp;
while ( *root ) {
temp = GetCode(cmp->cst, (*root)->cNum);
temp1 = GetCode(cmp->cst, code);
size = (temp1.size < temp.size) ? temp1.size : temp.size;
comp = memcmp(temp1.data, temp.data, size);
if (comp ==0 ) comp = (temp1.size < temp.size ) ? -1 : 1;
root = (comp < 0) ? &(*root)->left
: &(*root)->right;
}
*root = CreateNode(code);
}
注意:此代码不检查重复项。它总是插入一个节点。
注意2:我不确定登录:if (comp ==0 ) comp = (temp1.size < temp.size ) ? -1 : 1;
(在原文中,两种情况下的标志相同)