更改二叉树中的节点的影响

发布于 2024-08-28 16:27:05 字数 734 浏览 6 评论 0原文

假设我想更改以下树中的橙色节点。

因此,我需要进行的唯一其他更改是绿色节点左指针

蓝色节点将保持不变。

alt text

我在某个地方错了吗? 因为根据 这篇文章(解释拉链),甚至蓝色节点也需要更改。

同样,在这张图片(重新着色)中,来自同一篇文章< /a>, 为什么我们要更改橙色节点(当我们更改节点 x 时)?

替代文本

Suppose I want to change the orange node in the following tree.

So, the only other change I'll need to make is in the left pointer of the green node.

The blue node will remain the same.

alt text

Am I wrong somewhere? Because according to this article (that explains zippers), even the blue node needs to be changed.

Similarly, in this picture (recolored) from the same article, why do we change the orange nodes at all (when we change node x)?

alt text

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

能怎样 2024-09-04 16:27:05

在命令式语言中,你是正确的,只需要更改绿色节点。然而,对于纯函数式数据结构来说,情况并非如此。为了更改橙色节点,您需要更改绿色节点。因为您更改了绿色节点,所以您需要更改蓝色节点(依此类推)。实际上,“更改”这个词是不正确的,您实际上是在复制相关数据并创建一个新节点。因此,蓝色节点并没有被更改,而是创建了一个新的蓝色节点(指向新的绿色节点)。

这样做可以保持持久性,这意味着您可以存储树的所有先前状态。如果您想在更改橙色节点之前和更改橙色节点之后存储树,则需要同时更改绿色和蓝色 - 否则两者将是同一棵树的副本。

在第二种情况下,同样的情况也适用,只是现在您还需要更改父指针。由于您已经更改了根节点,因此所有橙色节点都需要将其父节点指针设置为指向其新父节点。

编辑:为了澄清一点,这样想一下。在纯函数式语言中,您无法修改任何内容,只能创建新节点或复制它们。因此,当您想要更改橙色节点时,您实际上使用不同的数据创建了它的副本(“更改”)。现在,您需要绿色节点指向橙色节点,这需要您创建一个新的橙色节点 - 该节点指向新的绿色节点。蓝色节点也是如此。

In an imperative language you are correct, only the green node needs to be changed. However for purely functional data structures this is not the case. In order to change the orange node you need to change the green node. Because you changed the green node, you then need to change the blue node (and so on). Actually the word change is incorrect, you are really copying the relevant data and creating a new node. So The blue node isn't being changed so much as a new blue node (which points to the new green node) is being created.

Doing so maintains persistence, meaning that you can store all previous states of the tree. If you wanted to store the tree before changing the orange node and after changing the orange node, you'd need change both the green and blue - otherwise both would be copies of the same tree.

In the second case, the same thing applies, only now you also need to change parent pointers. Since you've changed the root node, all the orange nodes need to have their parent pointers set to point to their new parents.

Edit: to clarify a bit, think about it like this. In a purely functional language you can't modify anything, you can only create new nodes or copy them. So when you want to change the orange node, you actually make a copy of it with different data (the "change"). Now you need the green node to point to the orange node, which requires you to create a new orange node - this one pointing to the new green node. The same is true for the blue node.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文