''' This class implements a general tree object. Simon D. Levy CSCI 315 01 NOV 2007 ''' # helper class class Branch: def __init__(self, tree, label): self.tree = tree self.label = label class Tree: # Constructs a tree node with specified contents and no children. def __init__(self, contents): self.contents = contents self.children = [] # Adds a labeled branch to this tree node. def addBranch(self, branch, label): self.children.append(Branch(branch, label)) # Returns True if tree is terminal (has no children), False otherwise. def isTerminal(self): return len(self.children) == 0 # Returns children of this tree. Terminal tree returns null. def getChildren(self): return children # Returns contents of this tree node. def getContents(self): return self.contents # Returns tree node on labeled branch. For duplicate labels, # returns first such node. Throws an exception if node is terminal or # label is bogus. def getBranch(self, label): if (self.isTerminal()): raise Exception('Node is terminal') for child in self.children: if child.label == label: return child.tree raise Exception('Label not found') # Returns a string representation of this tree. Each node in the # tree appears on a separate line, with depth indicated by indentation. def __str__(self, depth=0): s = str(self.contents) + '\n' for child in self.children: s = s + self._pad(depth+1) + child.label + ' : ' + child.tree.__str__(depth+1) return s def _pad(self, n): s = '' for i in range(0, n): s += ' ' return s