Python 在二元搜索树中只计算一个子节点数?

Python 在二元搜索树中只计算一个子节点数?,python,recursion,binary-search-tree,Python,Recursion,Binary Search Tree,如何计算二叉搜索树中只有一个子节点的节点数 def one_child_count(self): node = self._root count = self.one_child_count_aux(node) return count def one_child_count_aux(self,node): count = 0 if node : if node._left is not None and node._right is

如何计算二叉搜索树中只有一个子节点的节点数

def one_child_count(self):

    node = self._root
    count = self.one_child_count_aux(node)
    return count
def one_child_count_aux(self,node):
    count = 0
    if node :
        if node._left is not  None and  node._right is None: 

            count += 1
        if node._right is not  None and  node._left is None: 

            count += 1

        else:
            if node._left: 
                count += self.leaf_count_aux(node._left) 
            if node._right: 
                count += self.leaf_count_aux(node._right) 
    return count 
我不知道我做错了什么。当我尝试运行代码并插入:

bst.insert(37)
bst.insert(12)
这棵树就像:

  37
 /
12 
它应该返回1,但我得到2。请帮我更正代码。

您可以使用getattr实现更简洁的递归函数:

class Tree:
  def __init__(self, **kwargs):
    self.__dict__ = {i:kwargs.get(i) for i in ['val', '_left', '_right']}
  def count_nodes(self):
    yield 1
    yield from getattr(self._left, 'count_nodes', lambda :[])()
    yield from getattr(self._right, 'count_nodes', lambda :[])()

t = Tree(_left = Tree(val = 12), val = 37)
result = sum(t.count_nodes())
输出:

2

如果您仍然使用递归,那么可以使用一个通用的递归函数来计算一个或两个子节点

def count_nodes(bst):
    def count_nodes2(node):
        if node is None:
            return 0
        return 1 + count_nodes2(node._left) + count_nodes2(node._right)

    return count_nodes2(bst._root)
代码有两个问题:第一,if语句中关于使用else的逻辑错误;其次,调用unshawn函数leaf\u count\u aux,使其不是递归的,而不是递归地调用一个子函数leaf\u count\u aux。我猜你想要的东西更像:

def one_child_count(self):
    node = self._root
    count = self.one_child_count_aux(node)
    return count

def one_child_count_aux(self, node):
    count = 0

    if node:
        if node._left is not None:
            if node._right is None:
                count += 1

            count += self.one_child_count_aux(node._left)

        if node._right is not None:
            if node._left is None:
                count += 1

            count += self.one_child_count_aux(node._right)

    return count

什么是leaf\u count\u aux?很抱歉我发现了这个错误,谢谢你指出@Adam Smith它现在起作用了:那是一个愚蠢的错误tho