查找给定级别的节点数的不同方法

时间:2017-08-03 05:27:01

标签: python

我有一个家庭工作问题,要求我找到给定级别的节点数(函数的参数)。现在我知道之前有过很多类似的问题。我尝试了答案,但它对我不起作用。所以我需要来自社区的意见来告诉我我做错了什么以及我可以解决这个问题的其他方法。这就是我所拥有的:

def nodes_at_level(tnode, desired_level):
    """
    Purpose:
        Return the number of nodes in the tree at the given level.
    Pre-conditions:
        :param treenode: a treenode
        :param level: a non-negative integer
    Return:
        The number of nodes at the given level.
   """
   if tnode is None:
      return
   elif desired_level == 0:
       return
   else:
       return nodes_at_level(tn.get_left(tnode), desired_level - 1) \
      + nodes_at_level(tn.get_right(tnode), desired_level - 1)

tn只是作为字典实现的树节点adt。

1 个答案:

答案 0 :(得分:0)

def nodes_at_level(tnode, desired_level):
    """
    Purpose:
        Return the number of nodes in the tree at the given level.
    Pre-conditions:
        :param treenode: a treenode
        :param level: a non-negative integer
    Return:
        The number of nodes at the given level.
   """
   if tnode is None:
      return 0
   elif desired_level == 0:
       return 1
   else:
       return nodes_at_level(tn.get_left(tnode), desired_level - 1) \
      + nodes_at_level(tn.get_right(tnode), desired_level - 1)