我正在尝试建立一个段树,其父节点应包含其子节点的最小值和最大值。现在,当我尝试实现此功能时,我面临一个错误,即一个子节点可以返回整数,而另一个子节点可以返回列表,并且操作max或min函数将引发错误。如何克服此问题?
from math import log2,ceil
def segment(low,high,pos):
if (low==high):
segment_tree[pos]=arr[low]
return
mid=(high+low)//2
segment(low,mid,2*pos+1)
segment(mid+1,high,2*pos+2)
segment_tree[pos]=[min(segment_tree[2*pos+1],segment_tree[2*pos+2]),max(segment_tree[2*pos+1],segment_tree[2*pos+2])]
length=5
arr=[1,2,3,4,5]
low=0
high=length-1
height=int(ceil(log2(length)))
pos=0
size_of_segment_tree=2*int(pow(2,height))-1
segment_tree=[0]*size_of_segment_tree
segment(low,high,pos)
最佳答案
这将使用isinstance(object,list)工作
segment_tree[pos]=[min(min(segment_tree[2*pos+1]) if isinstance(segment_tree[2*pos+1],list) else segment_tree[2*pos+1],min(segment_tree[2*pos+2]) if isinstance(segment_tree[2*pos+2],list) else segment_tree[2*pos+2]),max(max(segment_tree[2*pos+1]) if isinstance(segment_tree[2*pos+1],list) else segment_tree[2*pos+1],max(segment_tree[2*pos+2]) if isinstance(segment_tree[2*pos+2],list) else segment_tree[2*pos+2])]
编辑:为清晰起见重新格式化:
segment_tree[pos]= [
min(min(segment_tree[2*pos+1])
if isinstance(segment_tree[2*pos+1],list)
else segment_tree[2*pos+1],
min(segment_tree[2*pos+2])
if isinstance(segment_tree[2*pos+2],list)
else segment_tree[2*pos+2]),
max(max(segment_tree[2*pos+1])
if isinstance(segment_tree[2*pos+1],list)
else segment_tree[2*pos+1],
max(segment_tree[2*pos+2])
if isinstance(segment_tree[2*pos+2],list)
else segment_tree[2*pos+2])
]