微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从两个数组构建树

如何解决从两个数组构建树

如果我们给出了两个表示相应节点如何连接的数组,如何编码以构建二叉树。假设树的根从元素 1 开始。

Ex -> arr1[] = {1,1,5,8,25}
      arr2[] = {4,6,5}

                               1
                             /   \
                            4     5
                                 / \
                                8   25
                               /
                              6

解决方法

使用一个映射来存储每个数字对应的节点,这将简化任务。算法看起来像这样:

# initialise the map
map = {}
for element in arr1:
    if element not in map:
        map[element] = new_node()
for element in arr2:
    if element not in map:
        map[element] = new_node()

# each node will have a data value,and left/right pointers to children
for i in range (len(arr1)):
    parent,child = arr1[i],arr2[i]
    if map[parent].left == None:
        map[parent].left = child
    else map[parent].right = child

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。