def spt_height(spt: SimplePrefixTree) -> int: """Return the height of the spt Precondition: spt is not an empty SimplePrefixTree """ if spt.is_leaf(): # an internal node with only 1 leaf return 1 else: # spt is not a leaf count = 1 for subtree in spt.subtrees: height = spt_height(subtree) if height >= count: count = height + 1 # + 1 including the own tree return count
def num_nodes(spt: SimplePrefixTree) -> int: """Return the number of nodes an SPT has >>> spt = SimplePrefixTree('sum') >>> spt.insert('x', 1, ['x']) >>> num_nodes(spt) 3 >>> spt.insert('che', 3,['c','h','e']) >>> num_nodes(spt) 7 >>> spt.insert('xenon', 2, ['x','e','n','o','n']) >>> num_nodes(spt) 12 """ if spt.weight == 0: return 1 elif spt.is_leaf(): return 1 else: # it's an internal node count = 1 for subtree in spt.subtrees: count += num_nodes(subtree) return count