我对二叉搜索树插入操作中的递归部分感到困惑。
bstnode* insert(bstnode* root,int data)
{
if(root==NULL){
bstnode* tmp= new bstnode();
tmp->data=data;
tmp->left=tmp->right=NULL;
return tmp;
}
if(data<root->data)
root->left = insert(root->left, data);
else
root->right = insert(root->right, data); //can't understand the logic here
return root;
}
/* consider following BST with their addresses[]:
15 [100]
/ \
10 20 [200]
\
tmp [300]
*/
根据我的理解,
root->right = insert(root->right, data);
应该将新创建的节点的地址存储在 root->right
中,因此这段代码不适用于高度大于2的树。
然而,对于任意数量的节点,它都可以完美地运行。
我一定漏掉了一些关键细节。
假设我想在BST中插入25,即insert(root,25);
由于25>15:-
我在这里分解递归部分:
root->right = insert(root->right, 25);
或者
15->right = insert(15->right,25);
这里再次递归调用它,因为25>20 insert(root->right, 25)
=> root->right->right
= insert(root->right->right, 25);
或者
insert(15->right, 25)
=> 20->right
= insert(20->right, 25);
insert(20->right,25)
是 NULL
,因此创建了一个新节点 tmp
。insert(20->right,25);
返回 tmp
。现在解开递归。
//20->right = insert(20->right, 25);
所以,
20->right=
300 (临时地址);//insert(15->right, 25) => 20->right
//and 15->right = insert(15->right,25);
15->right = 20->next;
因此,15->right
的值为[300]地址。
或者
root->right
的值为[300]地址。
我的方法有什么问题吗?
再次概述递归调用:
15->right = insert(15->right,25);
15->right = [20->right = insert(20->right,25)]; //20->right is NULL so creating new node
15->right = [20->right= 300 address of tmp];
15->right = [20->right or 300]
15->right = [300] // but in reality 15->right = [200]
insert(root->right, 25)
返回什么? - user253751