我已经找到了递归方法,但我似乎无法弄清楚如何迭代地在BST中插入元素。关于如何解决迭代方法,我不需要回答一点方向。谢谢!
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;
}
}
答案 0 :(得分:1)
static NODE * insert_i(NODE **rr, int x)
{
while (*rr) {
if((*rr)->val == x) break;
rr = (x < (*rr)->val) ? &(*rr)->left : &(*rr)->right;
}
if(*r) return *r; /* duplicate */
(*rr) = malloc(sizeof **r);
(*rr)->left = NULL;
(*rr)->right = NULL;
(*rr)->val = x;
return *rr
}
被称为:
NODE *root=NULL, pp;
pp = insert_i( &root, 1234);