简体   繁体   English

在 O(n) 中创建二叉树

[英]Create a binary tree in O(n)

I have a sequence with n numbers and i want to create a data structure to answer the following question: sequence n = [5,7, 4, 24, 8, 3, 12, 34] I want the min(2,5) then the answer is 3 because a2=7, a3=4, a4=24, a5=8 .我有一个带有 n 个数字的序列,我想创建一个数据结构来回答以下问题:序列n = [5,7, 4, 24, 8, 3, 12, 34]我想要min(2,5)那么答案是 3 因为a2=7, a3=4, a4=24, a5=8 So the min(i,j) returns the position of minimum number between (i,j).因此 min(i,j) 返回 (i,j) 之间最小数的 position。 I thought that a good data structure to save this sequence would be a complete binary tree to save the sequence numbers at leaves.我认为保存这个序列的一个好的数据结构是一个完整的二叉树来保存叶子的序列号。 But how can i implement this structure in O(n)?但是我怎样才能在 O(n) 中实现这个结构呢?

All you need is a Segment Tree with range minimum query.您只需要一个具有范围最小查询的段树。 Here is detailed explanation of it. 是它的详细解释。 Building time is O(n) , because there are in tree no more than 2 * n nodes, so final time complexity will be O(n) .构建时间为O(n) ,因为树中不超过2 * n节点,所以最终时间复杂度为O(n)

If you need to find not only the minimum value, but also the position, then inside the vertex you need to store not only the minimum, but also where it was reached.如果您不仅需要找到最小值,还需要找到 position,那么在顶点内部,您不仅需要存储最小值,还需要存储达到的位置。 How to update such a structure seems clear: when you recalculate the minimum in the father, you need to see from which son it is received and take the corresponding position of the minimum from the son.如何更新这样的结构似乎很清楚:当您重新计算父亲中的最小值时,您需要查看它是从哪个儿子接收的,并从儿子那里获取最小值对应的 position。 For leaves, the positions are equal to the positions of the leaves themselves.对于叶子,位置等于叶子本身的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM