我正在经历从二叉搜索树删除节点的代码,我有点糊涂了递归:传递给函数的变量是否需要跟踪和更新?
Node deleteRec(Node root, int key)
{
/* Base Case: If the tree is empty */
if (root == null) return root;
/* Otherwise, recur down the tree */
if (key < root.key)
root.left = deleteRec(root.left, key);
else if (key > root.key)
root.right = deleteRec(root.right, key);
// if key is same as root's key, then This is the node
// to be deleted
else
{
// node with only one child or no child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
// node with two children: Get the inorder successor (smallest
// in the right subtree)
root.key = minValue(root.right);
// Delete the inorder successor
root.right = deleteRec(root.right, root.key);
}
return root;
}
为什么我们需要存储结果的功能在root.left
和root.right
变量在几个地方调用?由于root
的值即传递给函数,随后调用中的任何更改都会自动更新树,是不是?那么为什么要将这些值存储在变量中呢?为了让下面我一点明确的是另一段代码
// A recursive function used by topologicalSort
void topologicalSortUtil(int v, boolean visited[],
Stack stack)
{
// Mark the current node as visited.
visited[v] = true;
Integer i;
// Recur for all the vertices adjacent to this
// vertex
Iterator<Integer> it = adj[v].iterator();
while (it.hasNext())
{
i = it.next();
if (!visited[i])
topologicalSortUtil(i, visited, stack);
}
// Push current vertex to stack which stores result
stack.push(new Integer(v));
}
这里堆被传递给函数,我们只是一遍又一遍用它在进一步的函数调用,因为我们知道,堆栈将继续跨越更新调用。
我错过了什么,或者我明白了什么错?有人可以帮助我理解。谢谢 !!
”最简单的情况是当删除的节点是叶:在这种情况下,指向它的链接必须设置为空。“感谢你的回答。所有的答案都很有帮助,但是这条线让我很清楚。干杯! – varunkr