返回一个包含内部节点数和叶数的元组

时间:2013-12-02 18:32:47

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

如何返回包含内部节点数和叶数的元组? 以下是我到目前为止所得到的,但它似乎没有正常工作。

另外,有没有人知道一个好网站,我可以学习二叉树和递归问题集以进行更多练习?

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)

1 个答案:

答案 0 :(得分:2)

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)