【问题标题】:Count nodes with only one child in a Binary Search Tree?计算二叉搜索树中只有一个孩子的节点?
【发布时间】:2018-07-11 15:47:28
【问题描述】:

我应该如何计算二叉搜索树中只有一个孩子的节点?

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。请帮助我更正我的代码。

【问题讨论】:

  • 什么是leaf_count_aux
  • 很抱歉我发现了这个错误感谢您指出@Adam Smith 它现在正在工作:) 这是一个愚蠢的错误

标签: python recursion binary-search-tree


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    您的代码存在两个问题:首先,您的if 语句中存在与使用else 相关的逻辑错误;其次,您正在调用未显示的函数leaf_count_aux(),使其不是递归的,而不是递归调用one_child_count_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
    

    【讨论】:

      【解决方案3】:

      您可以使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-23
        相关资源
        最近更新 更多