图像数据结构

发布于 2024-12-21 23:58:48 字数 177 浏览 1 评论 0原文

图像(方形图像)可以存储为树:如果图像是白色,则节点为白色,如果图像为黑色,则节点为黑色,如果包含两者,则为混合。白色和黑色节点是叶子,而混合节点将恰好有 4 个子节点,代表图像中的 4 个象限。给定 2 个图像(树),找到代表它们交集的图像。 (交集:B^B -> B、B^W -> W、W^W->W) 这是谷歌面试问题

An image(square image) can be stored as a tree: A node is white if the image is white, is black if the image is black, and is mixed if it contains both. White and black nodes are leaves, whereas a mixed node will have exactly 4 children, representing the 4 quadrants in the image. Given 2 images (trees), find the image representing their intersection. (Intersection: B^B -> B, B^W -> W, W^W->W)
This is a Google Interview Question

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

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

发布评论

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

评论(2

小霸王臭丫头 2024-12-28 23:58:48

这是一个简单的方法:使用相同的顺序同时遍历两棵树。在执行此操作时构建输出树。然后:

  1. 如果在两棵树中看到混合节点,则输出混合节点
  2. 如果在一棵树中看到混合节点,但在另一棵树中看到白色节点,则输出白色节点(并在遍历中忽略混合节点)
  3. 如果在一棵树中看到一个混合节点,但在另一棵树中看到一个黑色节点,将混合节点及其子节点复制到输出树中
  4. 如果看到两个白色节点,则输出一个白色节点
  5. 如果看到两个黑色节点,则输出一个黑色节点

这有可能创建一个实际上的混合节点只有白人孩子,所以你可能需要一个压缩步骤,遍历树折叠只有白人孩子的混合节点。

编辑:我认为您可以通过让递归知道下面是否找到输出黑色节点(如果答案是否定的,则放入白色叶子)来避免压缩步骤。

Here's a simple way to do it: Traverse both trees at the same time, using the same ordering. Build up an output tree while you do that. Then:

  1. If you see a mixed node in both trees, output a mixed node
  2. If you see a mixed node in one tree, but a white node in the other, output a white node (and ignore the mixed node in the traversal)
  3. If you see a mixed node in one tree, but a black node in the other, copy the mixed node and it's children to the output tree
  4. If you see two white nodes, output a white node
  5. If you see two black nodes, output a black node

This has the possibility to create a mixed node that's actually only got white children, so you probably want a compression step where you traverse the tree collapsing mixed nodes that only have white children.

Edit: I think you could avoid the compression step by letting your recursion know whether output black nodes were found below (and putting in a white leaf if the answer was no).

热风软妹 2024-12-28 23:58:48

由于两者都表示为二叉树,因此您必须从根开始遍历树结构,并随时检查两棵树中节点的颜色并将结果存储在另一棵树中。如果其中一个是黑色或白色,您将停止进一步遍历。否则,如果其中任何一个是混合的,则在该节点中进一步遍历,直到找到它们都是单色的。

Since both are represented as a binary tree you have to traverse a tree structure starting from root and check whats the color of nodes in both trees at any time and store the result in another tree. If either are black or white you stop traversing further. Else if anyone of them is mixed traverse further in that node until you find both of them of single color.

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