0
我已经找到了递归方法,但我似乎无法弄清楚如何在BST中迭代插入元素。关于如何解决迭代方法,我不需要答案。谢谢!BST插入迭代方法(C)
static NODE * insert(NODE *r, int x) //recursive approach
{
NODE *leaf;
if(r == NULL)
{
leaf = malloc(sizeof(NODE));
leaf->left = NULL;
leaf->right = NULL;
leaf->val = x;
return leaf;
}
if(r->val == x)
return r;
if(x < r->val)
{
r->left = insert(r->left, x);
return r;
}
else
{
r->right = insert(r->right, x);
return r;
}
}
static NODE *insert_i(NODE *r, int x) //iterative approach
{
NODE *leaf;
if(r == NULL)
{
leaf = malloc(sizeof(NODE));
leaf->left = NULL;
leaf->right = NULL;
leaf->val = x;
return leaf;
}
}
把最后两个if语句为while循环。 – this