问题描述
如果我们给出了两个表示相应节点如何连接的数组,如何编码以构建二叉树。假设树的根从元素 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