如何返回一个包含内部节点数和叶子数的元组?以下是到目前为止我得到的,但似乎无法正常工作。
此外,有人知道一个好的网站,我可以在其中学习二叉树和带有问题集的递归以进行更多练习吗?
class BTNode:
'''Node in binary tree'''
def __init__(self, value, left, right):
'''
Create new BTNode with value and possible children left and right'''
self.value, self.left, self.right = value, left, right
def count_nodes(n:'BTNode') -> (int, int):
'''
Return a tuple containing the number of interior nodes and the number of
leaves in the tree rooted at n, or (0,0) if n is None.
'''
if not n:
return (0,0)
else:
left_internal, left_leaves = count_nodes(n.left)
right_internal, right_leaves = count_nodes(n.right)
internal, leaf = (1 if n.left or n.right else 0,
1 if not n.left and not n.right else 0)
return (left_internal + right_internal + internal,
left_leaves + right_leaves + leaf)
class BTNode:
'''Node in binary tree'''
def __init__(self, value, left=None, right=None):
'''
Create new BTNode with value and possible children left and right
'''
self.value, self.left, self.right = value, left, right
def count_nodes(self):
'''
Return a tuple containing the number of interior nodes and the number of
leaves in the tree rooted at n, or (0,0) if n is None.
'''
if self.left is None and self.right is None:
# leaf
return (0, 1)
else:
# internal node
left_nodes, left_leaves = (0, 0) if self.left is None else self.left.count_nodes()
right_nodes, right_leaves = (0, 0) if self.right is None else self.right.count_nodes()
return (left_nodes + 1 + right_nodes, left_leaves + right_leaves)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句