【发布时间】:2015-05-20 14:12:05
【问题描述】:
我在理解二叉搜索树插入的递归部分时遇到了一些麻烦。
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(tmp地址);
//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]
【问题讨论】:
-
root->right = root->right->right = tmp;- 第一个root->right =来自哪里?好像是从哪里冒出来的…… -
它来自条件 25>15
-
错误...
insert(root->right, 25)返回什么? -
这是一个递归函数,在达到基本情况后,它返回设置为 root->right->right 的新节点,然后再次展开到 root->right
-
杰瑞你忘记了当它展开时返回到上一个函数的指针已经从它上面级别的根目录更改了一个
标签: c++ c algorithm recursion data-structures