在通过以下算法处理元素之后,我需要从数组创建树:
1. let A[n] be the array
2. while lenght(A) > 1
3. for i = 0 to lenght(A)-2
4. new_A[i] = max(A[i], A[i+1]) + 1
5. end for
6. [minValue, minIndex] = someFunction(new_A) // someFunction returns the minimum value and index of the same
7. delete A[minIndex] and A[minIndex + 1] from A and insert minValue in that place // basically A[minIndex] and A[minIndex + 1] are being replaced by minValue
8. // This is how the length of A is being decreased by 1 in each iteration
9. end while
例:
+--------------+----------------------+-----------------+---------------+
| iteration No | Array A | Array new_A | Remarks |
+--------------+----------------------+-----------------+---------------+
| 1 | 5-9-3-2-1-6-8-3 |10-10-4-3-7-9-9 | minValue = 3 |
| | | | minIndex = 3 |
+--------------+----------------------+-----------------+---------------+
| 2 | 5-9-3-3-6-8-3 |10-10-4-7-9-9 | minValue = 4 |
| | | | minIndex = 2 |
+--------------+----------------------+-----------------+---------------+
| 3 | 5-9-4-6-8-3 |10-10-7-9-9 | minValue = 7 |
| | | | minIndex = 2 |
+--------------+----------------------+-----------------+---------------+
| 4 | 5-9-7-8-3 |10-10-9-9 | minValue = 9 |
| | | | minIndex = 2 |
+--------------+----------------------+-----------------+---------------+
| 5 | 5-9-9-3 |10-10-10 | minValue = 10 |
| | | | minIndex = 0 |
+--------------+----------------------+-----------------+---------------+
| 6 | 10-9-3 |11-10 | minValue = 10 |
| | | | minIndex = 1 |
+--------------+----------------------+-----------------+---------------+
| 7 | 10-10 |11 | minValue = 11 |
| | | | minIndex = 0 |
+--------------+----------------------+-----------------+---------------+
| 8 | 11 |-- | -- |
+--------------+----------------------+-----------------+---------------+
到此为止一切都还好。但是我需要用树来表示。结果树将如下所示:
iteration# 8 11
/ \
/ \
iteration# 7 / \------- 10
/ / \
iteration# 6 10