Python 最大堆中子树的最小值
给定最大堆作为一棵树,我必须为每个节点在其子树中找到一个最小值。F.ePython 最大堆中子树的最小值,python,recursion,heap,Python,Recursion,Heap,给定最大堆作为一棵树,我必须为每个节点在其子树中找到一个最小值。F.e 5 1 + + | | | | 4<--+--&g
5 1
+ +
| |
| |
4<--+-->3 1<--+->3
+ + +---> + +
| | | |
| +--+-->N | +-->N
2<-+-->1 | 2<---+->1 |
+ + +-->N + + +-->N
| | | |
| | N<+>N N<+>N
N<-+>N N<+-->N
在python中:
def sub_rec(node):
if node == None:
return 0
if node.right != None and node.left != None:
return min(node.right.key,node.left.key)
if node.right == None and node.left != None:
return node.left.key
if node.left == None and node.right != None:
return node.right.key
if node.left == None and node.right == None:
return node.key
x = sub_rec (node.left)
y = sub_rec (node.right)
return min(x,y)
`在有机会递归到左、右节点之前,您的代码返回左、右节点的最小值。
这应该是另一种方式 我会像这样重写它(未经测试):
def列表最小值(列表):
''返回忽略None元素的列表的最小值,如果没有值,则返回None'
mn=无
对于列表uu或[]中的li:
如果李!=无和(mn==无或li
def sub_rec(node):
if node == None:
return 0
if node.right != None and node.left != None:
return min(node.right.key,node.left.key)
if node.right == None and node.left != None:
return node.left.key
if node.left == None and node.right != None:
return node.right.key
if node.left == None and node.right == None:
return node.key
x = sub_rec (node.left)
y = sub_rec (node.right)
return min(x,y)
def list_min(list_):
''' returns the minimum value for the list ignoring None elements, or None if there are no values '''
mn = None
for li in list_ or []:
if li != None and (mn==None or li < mn):
mn=li
return mn
def sub_rec(node):
if node == None:
return None
return list_min(sub_rec(node.left), sub_rec(node.right), node.key)