【问题标题】:Counting nodes in a binary tree recursively递归计算二叉树中的节点
【发布时间】:2020-02-21 05:17:12
【问题描述】:

我必须递归地计算二叉树中的节点。我是 python 新手,找不到任何解决方案来完成我的代码。

这是我已经尝试过的。如您所见,它不完整,我不知道该去哪里。

class Tree:
    def __init__(self, root):
        self.root = root

    def add(self, subtree):
        self.root.children.append(subtree)

class Node:
    def __init__(self, value, children=None):
        self.value = value
        self.children = children if children is not None else []

def check_root(tree):
    if tree.root is None:
        return 0
    if tree.root is not None:
        return count_nodes(tree)

def count_nodes(tree):
    if tree.root.children is not None:
        j = 0
        for i in tree.root.children:
            j = 1 + count_nodes(tree)
        return j


print(count_nodes(Tree(None))) # 0
print(count_nodes(Tree(Node(10)))) # 1
print(count_nodes(Tree(Node(5, [Node(6), Node(17)])))) #3

每迈出新的一步,我都会遇到不同的错误。例如。使用此代码,我已经超过了最大递归深度。

感谢您抽出宝贵时间阅读本文。任何提示或帮助下一步做什么将不胜感激。

【问题讨论】:

    标签: python recursion binary-tree


    【解决方案1】:

    我首先将根节点传递给count_nodes 函数 -

    print(count_nodes(Tree(None)).root) # 0
    print(count_nodes(Tree(Node(10))).root) # 1
    print(count_nodes(Tree(Node(5, [Node(6), Node(17)]))).root) #3
    

    或为此创建一个辅助函数。

    那么count_nodes 函数可以简单地看起来像这样

    def count_nodes(node):
        return 1 + sum(count_nodes(child) for child in node.children)
    

    编辑:我刚刚注意到,您可以拥有None 根,这意味着您还应该处理:

    def count_nodes(node):
        if node is None:
            return 0
        return 1 + sum(count_nodes(child) for child in node.children)
    

    如果你真的想在一个函数中处理树或节点,你可以让它更丑一点:

    def count_nodes(tree_or_node):
        if isinstance(tree_or_node, Tree):
            return count_nodes(tree_or_node.root)
        if tree_or_node is None:
            return 0
        return 1 + sum(count_nodes(child) for child in tree_or_node.children)
    

    然后你就可以像原来那样调用它了。

    【讨论】:

      【解决方案2】:

      您的问题是您无限地计算同一棵树。看看这一行:

      j = 1 + count_nodes(tree)
      

      【讨论】:

        【解决方案3】:

        简单的方法:

        让我们假设,A 是一棵二叉树,其子节点或节点不是 NULL。例如

             3  
            / \  
          7     5  
           \     \  
           6       9  
          / \     /  
         1  11   4 
        

        现在为了计算节点的数量,我们有一个简单的解决方法。

        递归方法:>>> get_count(root)

        对于二叉树,递归的基本思想是后序遍历树。这里,如果当前节点已满,我们将结果递增1,并添加左右子树的返回值,如:

        class TestNode(): 
        
        
        def __init__(self, data):  
            self.data = data 
            self.left = None
            self.right = None
        

        现在我们继续使用下面的方法来获取二叉树中完整节点的数量:

        def get_count(root): 
        
          if (root == None): 
            return 0
        
          res = 0
          if (root.left and root.right): 
             res += 1
        
          res += (get_count(root.left) + 
                get_count(root.right))  
          return res  
        

        最后,为了运行代码,我们将管理一个主作用域: 在这里,我们创建了我们的 二叉树 A,如上所示:

        if __name__ == '__main__': 
        
          root = TestNode(3)  
          root.left = TestNode(7)  
          root.right = TestNode(5)  
          root.left.right = TestNode(6)  
          root.left.right.left = TestNode(1)  
          root.left.right.right = TestNode(4)
        

        现在最后,在主范围内,我们将打印二叉树节点的计数,例如:

          print(get_Count(root)) 
        

        这是此递归函数获取二叉树 A 的计数的时间复杂度。

        时间复杂度:O(n)

        【讨论】:

          猜你喜欢
          • 2015-08-31
          • 2014-08-12
          • 2014-05-10
          • 2018-10-30
          • 1970-01-01
          • 2020-09-04
          • 2015-09-02
          • 1970-01-01
          • 2023-03-25
          相关资源
          最近更新 更多