从头开始构建二叉树

时间:2019-03-06 15:55:45

标签: python algorithm tree binary-tree

考虑以下程序,该程序通过将节点分为两半,从上到下构建一棵二叉树:

def split(n):
    if n == 1:
        return n
    m = n//2
    return [split(n-m)] + [split(m)]

例如:

for i in range(1, 10):
    print(i, split(i))

打印:

1 1
2 [1, 1]
3 [[1, 1], 1]
4 [[1, 1], [1, 1]]
5 [[[1, 1], 1], [1, 1]]
6 [[[1, 1], 1], [[1, 1], 1]]
7 [[[1, 1], [1, 1]], [[1, 1], 1]]
8 [[[1, 1], [1, 1]], [[1, 1], [1, 1]]]
9 [[[[1, 1], 1], [1, 1]], [[1, 1], [1, 1]]]

是否可以从下往上构建完全相同的树?也就是说,在给定数量1的情况下,递归合并两个相邻节点,直到没有更多要合并的内容了?

如果没有,是否有可能从下往上构建高度完全相同的类似树?

为说明该过程,请以6为例:

1, 1, 1, 1, 1, 1
[1, 1], 1, 1, 1, 1
[1, 1], 1, [1, 1], 1
[[1, 1], 1], [1, 1], 1
[[1, 1], 1], [[1, 1], 1]
[[[1, 1], 1], [[1, 1], 1]]

我怎么知道何时“跳过”节点以便稍后合并?

PS:该示例使用Python,但语言无关紧要。

1 个答案:

答案 0 :(得分:0)

Let n be the initial size of the array 
for(int i=0;i<log2(n);i++)
{
    Let the current size of the array be m
    for(int j=0;j<m/2;j++)
        merge two adjacent elements of the array to form a new element
    // After this some elements from first half would be single

    for(int j=m/2;j<m;j++)
        merge two adjacent elements of the array to form a new element.  
    // After this some elements from second half would be single

    // The new updated array will now have ceil(n/2) elements
}