【问题标题】:Counting different types of nodes in a Binary Search Tree计算二叉搜索树中不同类型的节点
【发布时间】:2015-05-14 04:14:37
【问题描述】:

我正在尝试编写一个计算不同类型节点的递归函数:

  • 具有零子节点的节点数
  • 一个孩子的节点数
  • 有两个孩子的节点数

    def _node_counts_aux(self,node):
    
        zero = 0
        one = 0
        two = 0
    
        if node is not None:     
            #print("==========")
            #print(node)
            #print(node._left)
            #print(node._right)
            #print()
    
            # Two children case
            if node._left is not None and node._right is not None:
                #print("Two")
                two = self._node_counts_aux(node._left)[2] + self._node_counts_aux(node._right)[2] + 1
    
            # One child case
            elif node._left is None and node._right is not None:
                #print("One")
                one = self._node_counts_aux(node._right)[1] + 1
    
            elif node._right is None and node._left is not None:
                #print("One")
                one = self._node_counts_aux(node._left)[1] + 1
    
            # Zero children case
            elif node._left is None and node._right is None:
                #print("Zero")
                zero = self._node_counts_aux(node._left)[0] + self._node_counts_aux(node._right)[0] + 1
    
        return zero, one, two
    

我相信if 语句结构涵盖了所有情况,但是当我使用这个 bst 运行我的程序时,我得到了这个结果:

Zero children: 0
One child:     0
Two children:  4

我使用 print 语句测试了我的程序,并确定我的递归调用存在问题。然而,问题是,一切(据我所知)都是正确的。有人可以指出我的错误吗?提前致谢

【问题讨论】:

  • _node_counts_aux()在哪里?
  • @avim 发布的代码是 _node_counts_aux()
  • 请编辑以便我们看到

标签: python-3.x recursion binary-tree


【解决方案1】:

您的函数实际上返回后续完整节点的数量。您应该保留每次呼叫的计数器信息。

def _node_counts_aux(self,node):
    # 'n[i]' is the total number of nodes with 'i' sons
    n = [0,0,0]
    sons = 0

    #one call for left 
    if node._left:
        n = [sum(x) for x in zip(n, self._node_counts_aux(node._left))]
        sons += 1

    #one call for right 
    if node._right:
        n = [sum(x) for x in zip(n, self._node_counts_aux(node._right))]
        sons += 1

    #count this node in the relevant counter 
    n[sons] += 1

    return n

更好(代码重用):

def _node_counts_aux(self,node):
    # 'n[i]' is the total number of nodes with 'i' sons
    n = [0,0,0]
    sons = 0

    for son_node in [node._left, node._right]:
        if son_node:
            n = [sum(x) for x in zip(n, self._node_counts_aux(son_node))]
            sons += 1

    #count this node in the relevant counter 
    n[sons] += 1

    return n

【讨论】:

  • 我应该说这个问题是作业,所以我必须返回零一和二
  • 没关系。您可以随意调用它:zero,one,two = obj._node_counts_aux(node)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 2014-05-10
  • 1970-01-01
相关资源
最近更新 更多