二进制搜索树中三种节点的计数(递归)

时间:2013-03-20 19:39:27

标签: python algorithm data-structures recursion binary-search-tree

我正在尝试编写一个函数来计算Python中二进制搜索树中的三种类型的节点。它将计算并返回包含0个子节点,1个子节点和2个子节点的节点总数。我注意到递归方法最适合这种而不是迭代方式。

def node_counts(self):
    """
    ---------------------------------------------------------
    Returns the number of the three types of nodes in a BST.
    Use: zero, one, two = bst.node_counts()
    -------------------------------------------------------
    Postconditions:
      returns
      zero - number of nodes with zero children (int)
      one - number of nodes with one child (int)
      two - number of nodes with two children (int)
    ----------------------------------------------------------
    """
    zero, one, two = self._node_counts_aux(self._root)
    return zero, one, two

def _node_counts_aux(self, node):
    zero, one, two = 0, 0, 0
    if node is not None:
        if not node._right and not node._left:
            zero = 1 # I understand that the problem is here.
        if node._left and node._right:
            two = 1 + self._node_counts_aux(node._left)[2] + self._node_counts_aux(node._right)[2]
        if node._left or node._right:
            one = 1 + self._node_counts_aux(node._left)[1] + self._node_counts_aux(node._right)[1]
    return zero, one, two

"""
I am testing with this Tree:
        36
       /  \
      /    \
     6      50
    / \     / \
   4   17  49  84
       /   /   / \
      12  42  65 85

The output with this code comes to: (0, 6, 4).

"""

一栏在某种意义上是错误的,但在某种意义上也是对的。那不是我关心的问题。 我关注的是零,不计算在内。 零被设置为0所以我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

问题是方法_node_counts_aux()会返回一个元组,但您尝试将1添加到其结果中。您必须从递归调用中提取类型0,1和2的元素的计数,并使用这些值。

答案 1 :(得分:1)

您必须累积递归调用的结果。这可以使用zero, one, two = map(sum, zip(result_right, result_left))完成,然后根据子项数添加相应的值。

请注意,我使用的是if/elif语句,否则当节点有两个孩子时,您的代码也会输入一个孩子的下一个if块。

def _node_counts_aux(self, node):
    zero, one, two = 0, 0, 0
    if node is not None:
        result_right = self._node_counts_aux(node._right)
        result_left = self._node_counts_aux(node._left)
        zero, one, two = map(sum, zip(result_right, result_left))
        if not node._right and not node._left:
            zero += 1
        elif node._left and node._right:
            two += 1
        elif node._left or node._right:
            one += 1
    return zero, one, two