class BST(object): def __init__(self): self._tree = BinaryTree.THE_EMPTY_TREE self._size = 0 def isEmpty(self): return len(self) == 0 def __len__(self): return self._size def __str__(self): return str(self._tree) def __iter__(self): return iter(self.inorder()) def find(self, target): """Returns data if target is found or None otherwise.""" def findHelper(tree): if tree.isEmpty(): return None elif target == tree.getRoot(): return tree.getRoot() elif target < tree.getRoot(): return findHelper(tree.getLeft()) else: return findHelper(tree.getRight()) return findHelper(self._tree) def add(self, newItem): """Adds newItem to the tree.""" # Helper function to search for item's position def addHelper(tree): currentItem = tree.getRoot() left = tree.getLeft() right = tree.getRight() # New item is less, go left until spot is found if newItem < currentItem: if left.isEmpty(): tree.setLeft(BinaryTree(newItem)) else: addHelper(left) # New item is greater or equal, # go right until spot is found elif right.isEmpty(): tree.setRight(BinaryTree(newItem)) else: addHelper(right) # End of addHelper # Tree is empty, so new item goes at the root if self.isEmpty(): self._tree = BinaryTree(newItem) # Otherwise, search for the item's spot else: addHelper(self._tree) self._size += 1 def remove(self, item): """Removes and returns item from the tree.""" # Helper function to adjust placement of an item def liftMaxInLeftSubtreeToTop(top): # Replace top's datum with the maximum datum in the left subtree # Pre: top has a left child # Post: the maximum node in top's left subtree # has been removed # Post: top.getRoot() = maximum value in top's left subtree parent = top currentNode = top.getLeft() while not currentNode.getRight().isEmpty(): parent = currentNode currentNode = currentNode.getRight() top.setRoot(currentNode.getRoot()) if parent == top: top.setLeft(currentNode.getLeft()) else: parent.setRight(currentNode.getLeft()) # Begin main part of the method if self.isEmpty(): return None # Attempt to locate the node containing the item itemRemoved = None preRoot = BinaryTree(None) preRoot.setLeft(self._tree) parent = preRoot direction = 'L' currentNode = self._tree while not currentNode.isEmpty(): if currentNode.getRoot() == item: itemRemoved = currentNode.getRoot() break parent = currentNode if currentNode.getRoot() > item: direction = 'L' currentNode = currentNode.getLeft() else: direction = 'R' currentNode = currentNode.getRight() # Return None if the item is absent if itemRemoved == None: return None # The item is present, so remove its node # Case 1: The node has a left and a right child # Replace the node's value with the maximum value in the # left subtree # Delete the maximium node in the left subtree if not currentNode.getLeft().isEmpty() \ and not currentNode.getRight().isEmpty(): liftMaxInLeftSubtreeToTop(currentNode) else: # Case 2: The node has no left child if currentNode.getLeft().isEmpty(): newChild = currentNode.getRight() # Case 3: The node has no right child else: newChild = currentNode.getLeft() # Case 2 & 3: Tie the parent to the new child if direction == 'L': parent.setLeft(newChild) else: parent.setRight(newChild) # All cases: Reset the root (if it hasn't changed no harm done) # Decrement the collection's size counter # Return the item self._tree = preRoot.getLeft() self._size -= 1 return itemRemoved # Traversal methods def inorder(self): """Returns a list containing the results of an inorder traversal.""" lyst = [] self._tree.inorder(lyst) return lyst def preorder(self): """Returns a list containing the results of a preorder traversal.""" lyst = [] self._tree.preorder(lyst) return lyst def postorder(self): """Returns a list containing the results of a postorder traversal.""" lyst = [] self._tree.postorder(lyst) return lyst def levelorder(self): """Returns a list containing the results of a levelorder traversal.""" lyst = [] self._tree.levelorder(lyst) return lyst
from binarytree import BinaryTree, Node def mirrorTree(root): if root is None: return root root.data = root.data root.left, root.right = root.right, root.left mirrorTree(root.left) mirrorTree(root.right) def mirrorTreeBU(root): if root is None: return root root.data = root.data mirrorTree(root.left) mirrorTree(root.right) root.left, root.right = root.right, root.left t = BinaryTree() t.insertLeft(5) t.insertLeft(4) t.insertRight(7) mirrorTreeBU(t.root) t.inorder()
from binarytree import BinaryTree from node import Node tree = BinaryTree(Node(6)) nodes = [5, 3, 9, 7, 8, 7.5, 12, 11] [tree.add(Node(n)) for n in nodes] tree.delete(9) tree.inorder()
class BST(object): def __init__(self): self._tree = BinaryTree.THE_EMPTY_TREE self._size = 0 def isEmpty(self): return len(self) == 0 def __len__(self): return self._size def __str__(self): return str(self._tree) def __iter__(self): return iter(self.inorder()) def find(self, target): """Returns data if target is found or None otherwise.""" def findHelper(tree): if tree.isEmpty(): return None elif target == tree.getRoot()[0]: return tree.getRoot()[1] elif target < tree.getRoot()[0]: return findHelper(tree.getLeft()) else: return findHelper(tree.getRight()) return findHelper(self._tree) def add(self, newItem): """Adds newItem to the tree.""" # Helper function to search for item's position def addHelper(tree): currentItem = tree.getRoot() left = tree.getLeft() right = tree.getRight() # New item is less, go left until spot is found if newItem[0] < currentItem[0]: if left.isEmpty(): tree.setLeft(BinaryTree(newItem)) else: addHelper(left) # New item is greater or equal, # go right until spot is found elif newItem[0] == currentItem[0]: tree.setRoot(newItem) elif right.isEmpty(): tree.setRight(BinaryTree(newItem)) else: addHelper(right) # End of addHelper # Tree is empty, so new item goes at the root if self.isEmpty(): self._tree = BinaryTree(newItem) # Otherwise, search for the item's spot else: addHelper(self._tree) self._size += 1 def inorder(self): """Returns a list containing the results of an inorder traversal.""" lyst = [] self._tree.inorder(lyst) return lyst def preorder(self): """Returns a list containing the results of a preorder traversal.""" lyst = [] self._tree.preorder(lyst) return lyst def postorder(self): """Returns a list containing the results of a postorder traversal.""" lyst = [] self._tree.postorder(lyst) return lyst def levelorder(self): """Returns a list containing the results of a levelorder traversal.""" lyst = [] self._tree.levelorder(lyst) return lyst def lookup(self, data, parent=None): def lookupHelper(tree, parent): value = tree.getRoot()[0] left = tree.getLeft() right = tree.getRight() if data < value: if left is None: return None, None if not left.isEmpty(): # print data, "->", left.getRoot() return lookupHelper(left, parent) else: return None, None elif data > value: if right is None: return None, None if not right.isEmpty(): # print data, "->", right.getRoot() return lookupHelper(right, parent) else: return None, None else: return tree, parent return lookupHelper(self._tree, parent) def remove(self, data): node, parent = self.lookup(data) value = node.getRoot()[1] #print n, parent if node is None: return None left = node.getLeft() right = node.getRight() children_count = 0 if not left.isEmpty(): children_count += 1 if not right.isEmpty(): children_count += 1 #print "children_count: ", children_count if children_count == 0: if parent is not None: if parent.getLeft() == node: parent.removeLeft() else: parent.removeRight() else: node.setRoot(None) elif children_count == 1: if not left.isEmpty(): n = left else: n = right if parent is not None: if parent.getLeft() == node: parent.setLeft(n) else: parent.setRight(n) else: node = n else: # find its successor parent = node successor = left while not successor.getRight().isEmpty(): parent = successor successor = successor.getRight() # replace node data by its successor data node.setRoot(successor.getRoot()) # fix successor's parent's child if parent.getLeft() == successor: parent._left = parent.getLeft().getLeft() else: parent._right = parent.getRight().getLeft() return value
class BST(object): def __init__(self): self._tree = BinaryTree.THE_EMPTY_TREE self._size = 0 def isEmpty(self): return len(self) == 0 def __len__(self): return self._size def __str__(self): return str(self._tree) def __iter__(self): return iter(self.inorder()) def find(self, target): """Returns data if target is found or None otherwise.""" def findHelper(tree): if tree.isEmpty(): return None elif target == tree.getRoot(): return tree.getRoot() elif target < tree.getRoot(): return findHelper(tree.getLeft()) else: return findHelper(tree.getRight()) return findHelper(self._tree) def add(self, newItem): """Adds newItem to the tree.""" # Helper function to search for item's position def addHelper(tree): currentItem = tree.getRoot() left = tree.getLeft() right = tree.getRight() # New item is less, go left until spot is found if newItem < currentItem: if left.isEmpty(): tree.setLeft(BinaryTree(newItem)) else: addHelper(left) # New item is greater or equal, # go right until spot is found elif right.isEmpty(): tree.setRight(BinaryTree(newItem)) else: addHelper(right) # End of addHelper # Tree is empty, so new item goes at the root if self.isEmpty(): self._tree = BinaryTree(newItem) # Otherwise, search for the item's spot else: addHelper(self._tree) self._size += 1 def remove(self, item): """Removes and returns item from the tree.""" # Helper function to adjust placement of an item def liftMaxInLeftSubtreeToTop(top): # Replace top's datum with the maximum datum in the left subtree # Pre: top has a left child # Post: the maximum node in top's left subtree # has been removed # Post: top.getRoot() = maximum value in top's left subtree parent = top currentNode = top.getLeft() while not currentNode.getRight().isEmpty(): parent = currentNode currentNode = currentNode.getRight() top.setRoot(currentNode.getRoot()) if parent == top: top.setLeft(currentNode.getLeft()) else: parent.setRight(currentNode.getLeft()) # Begin main part of the method if self.isEmpty(): return None # Attempt to locate the node containing the item itemRemoved = None preRoot = BinaryTree(None) preRoot.setLeft(self._tree) parent = preRoot direction = 'L' currentNode = self._tree while not currentNode.isEmpty(): if currentNode.getRoot() == item: itemRemoved = currentNode.getRoot() break parent = currentNode if currentNode.getRoot() > item: direction = 'L' currentNode = currentNode.getLeft() else: direction = 'R' currentNode = currentNode.getRight() # Return None if the item is absent if itemRemoved == None: return None # The item is present, so remove its node # Case 1: The node has a left and a right child # Replace the node's value with the maximum value in the # left subtree # Delete the maximium node in the left subtree if not currentNode.getLeft().isEmpty() \ and not currentNode.getRight().isEmpty(): liftMaxInLeftSubtreeToTop(currentNode) else: # Case 2: The node has no left child if currentNode.getLeft().isEmpty(): newChild = currentNode.getRight() # Case 3: The node has no right child else: newChild = currentNode.getLeft() # Case 2 & 3: Tie the parent to the new child if direction == 'L': parent.setLeft(newChild) else: parent.setRight(newChild) # All cases: Reset the root (if it hasn't changed no harm done) # Decrement the collection's size counter # Return the item self._tree = preRoot.getLeft() self._size -= 1 return itemRemoved # Traversal methods def inorder(self): """Returns a list containing the results of an inorder traversal.""" lyst = [] self._tree.inorder(lyst) return lyst def preorder(self): """Returns a list containing the results of a preorder traversal.""" lyst = [] self._tree.preorder(lyst) return lyst def postorder(self): """Returns a list containing the results of a postorder traversal.""" lyst = [] self._tree.postorder(lyst) return lyst def levelorder(self): """Returns a list containing the results of a levelorder traversal.""" lyst = [] self._tree.levelorder(lyst) return lyst
print "Size:", size(d) print "String:" print d print "Frontier:", frontier(d) print "Preorder:" lyst = [] d.preorder(lyst) print lyst print "Inorder:" lyst = [] d.inorder(lyst) print lyst print "Postorder:" lyst = [] d.postorder(lyst) print lyst print "Levelorder:" lyst = [] d.levelorder(lyst) print lyst print "Iterator:" for item in d: print item,
class BST(object): def __init__(self): self._tree = BinaryTree.THE_EMPTY_TREE self._size = 0 def isEmpty(self): return len(self) == 0 def __len__(self): return self._size def __str__(self): return str(self._tree) def __iter__(self): return iter(self.inorder()) def find(self, target): """Returns data if target is found or None otherwise.""" def findHelper(tree): if tree.isEmpty(): return None elif target == tree.getRoot(): return tree.getRoot() elif target < tree.getRoot(): return findHelper(tree.getLeft()) else: return findHelper(tree.getRight()) return findHelper(self._tree) def add(self, newItem): """Adds newItem to the tree.""" # Helper function to search for item's position def addHelper(tree): currentItem = tree.getRoot() left = tree.getLeft() right = tree.getRight() # New item is less, go left until spot is found if newItem < currentItem: if left.isEmpty(): tree.setLeft(BinaryTree(newItem)) else: addHelper(left) # New item is greater or equal, # go right until spot is found elif right.isEmpty(): tree.setRight(BinaryTree(newItem)) else: addHelper(right) # End of addHelper # Tree is empty, so new item goes at the root if self.isEmpty(): self._tree = BinaryTree(newItem) # Otherwise, search for the item's spot else: addHelper(self._tree) self._size += 1 def inorder(self): """Returns a list containing the results of an inorder traversal.""" lyst = [] self._tree.inorder(lyst) return lyst def preorder(self): """Returns a list containing the results of a preorder traversal.""" # Exercise pass def postorder(self): """Returns a list containing the results of a postorder traversal.""" # Exercise pass def levelorder(self): """Returns a list containing the results of a levelorder traversal.""" # Exercise pass def remove(self, item): # Exercise pass
def trimTree(root, minVal, maxVal): if root is None: return root root.left = trimTree(root.left, minVal, maxVal) root.right = trimTree(root.right, minVal, maxVal) if minVal <= root.data <= maxVal: return root if root.data > maxVal: return root.left if root.data < minVal: return root.right root.left() bt = BinaryTree() bt.insert(50) bt.insert(30) bt.insert(20) bt.insert(40) bt.insert(70) bt.insert(60) bt.insert(80) # bt.inorder() trimTree(bt.root, 30, 80) bt.inorder()
print "Size:", size(d) print "String:" print d print "Frontier:", frontier(d) print "Preorder:" lyst = [] d.preorder(lyst) print lyst print "Inorder:" lyst = [] d.inorder(lyst) print lyst print "Postorder:" lyst = [] d.postorder(lyst) print lyst print "Levelorder:" lyst = [] d.levelorder(lyst) print lyst print "Iterator:" for item in d: print item,