最大堆中的子树最小值

时间:2018-04-15 12:59:01

标签: python recursion heap

将最大堆作为树,我必须在每个节点的子树中找到最小值。 F.E.

          5                                    1
          +                                    +
          |                                    |
          |                                    |
      4<--+-->3                            1<--+->3
      +       +           +--->            +      +
      |       |                            |      |
      |       +--+-->N                     |      +-->N
   2<-+-->1      |                    2<---+->1   |
   +      +      +-->N                +       +   +-->N
   |      |                           |       |
   |      |                         N<+>N   N<+>N
N<-+>N  N<+-->N

2,1,3是指向NULL的叶子。这棵树的预期结果显然是1,但我的算法返回2(首次在asciiArt中绘制一棵树)。这是我的算法:    `

If node is None, return 0
If node has TWO children , return min(children1.key,children2.key)
If node has ONE children , return children.key
If node does NOT have children , return node.key
Go to left subtree
Go to right subtree
Return min

在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)

`

1 个答案:

答案 0 :(得分:0)

您的代码在有机会递归之前返回左侧和右侧节点的最小值 那应该是另一种方式。

我会像这样重写它(未经测试):

from IPython.display import Math
from sympy.interactive import printing
printing.init_printing(use_latex=True)
f=(-2*x-1)/(pow(x,2)+2)
Math('F(x)=')
integrate(f,x)
Math('+C')