【发布时间】:2015-02-19 08:14:51
【问题描述】:
我正在阅读以下文章。 Add greater values of every node
所以我对函数void modifyBSTUtil(struct node *root, int *sum)的疑问
returns ,为什么它所做的更改会持续存在于树中。
1.我们没有使用双指针
2.根也不是全局的
3.我们不返回地址
谁能解释为什么会这样??
代码
void modifyBSTUtil(struct node *root, int *sum)
{
// Base Case
if (root == NULL) return;
// Recur for right subtree
modifyBSTUtil(root->right, sum);
// Now *sum has sum of nodes in right subtree, add
// root->data to sum and update root->data
*sum = *sum + root->data;
root->data = *sum;
// Recur for left subtree
modifyBSTUtil(root->left, sum);
}
调用 : modifyBSTUtil(root, &sum)
插入函数
struct node* insert(struct node* node, int data)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(data);
/* Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
/* return the (unchanged) node pointer */
return node;
}
我们需要在插入函数的情况下返回地址以使更改永久化,为什么不在这里返回??
【问题讨论】:
-
也许指针在函数内部被取消引用。
-
你能给我们一个minimal complete exampole吗? (我真的应该有那个热键。)
-
你没有修改树结构;您正在修改已经存在的节点。您只需要一个根节点地址即可。