如何绘制此输入的二叉树:[1,2,2,3,null,null,3,4,null,null,4]?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
数组编码不能让您假设节点的子节点位于索引
i*2+1
和i*2+2
处。如果编码树是完整二叉树,则情况如此,但如果不是,则不能使用此公式。相反,您应该在构建树时跟踪树的底层,仅注册真实节点(而不是
null
)。然后将下一个子节点分布在(当时)底层的节点中,等等。这实际上是一种广度优先的遍历方法。过程如下:
创建一个队列,并为输入列表中的第一个值创建一个节点(如果列表不为空),并将其入队。
然后,只要有更多输入需要处理,就重复此操作:
null
。如果将此算法应用于示例输入 [1,2,2,3,null,null,3,4,null,null,4],那么我们首先得到根,并将其放入队列中。因此,就在循环开始之前,我们有:
我在这里用数字描述了队列内容,但它们实际上是节点实例。
在循环的第一次迭代之后,我们从输入中读取 2 和 2,为它们创建节点,将它们附加到出队节点,并将这些子节点入队,我们得到:
在迭代 #2 之后(请注意,没有 null 入队) ):
迭代#3之后:
迭代#5之后:
最终迭代之后:
队列不为空,但由于没有更多输入,这些排队的节点代表不需要进一步处理的叶子。
The array encoding is not such that you can assume that a node's children are at the index
i*2+1
andi*2+2
. That would be true if the encoded tree were a complete binary tree, but when it is not, you cannot use this formula.Instead, you should keep track of the bottom layer of the tree as you build it, only registering real nodes (not
null
). Then distribute the next children among the nodes in the (then) bottom layer, etc. This is really a breadth-first traversal method.This is the procedure:
Create a queue, and create a node for the first value in the input list (if the list is not empty), and enqueue it.
Then repeat for as long as there is more input to process:
null
instead.null
should be enqueued on the queue.If you apply this algorithm to the example input [1,2,2,3,null,null,3,4,null,null,4], then we get first the root, which is put on the queue. So just before the loop starts we have:
I depict here the queue contents with numbers, but they really are node instances.
After the first iteration of the loop, in which we read 2 and 2 from the input, create nodes for them, attach them to the dequeued node, and enqueue those children, we get:
After iteration #2 (note that no null is enqueued):
After iteration #3:
After iteration #5:
After the final iteration:
The queue is not empty, but as there is no more input, those queued nodes represent leaves that need no further processing.