Download Data Structures (CS 1520) Name:___________________________ / -

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Quadtree wikipedia , lookup

B-tree wikipedia , lookup

Lattice model (finance) wikipedia , lookup

Red–black tree wikipedia , lookup

Interval tree wikipedia , lookup

Binary tree wikipedia , lookup

Binary search tree wikipedia , lookup

Transcript
Data Structures (CS 1520)
Name:___________________________
1. Consider the parse tree for (9 + (5 * 3)) / (8 - 4):
/
-
+
9
*
5
8
4
3
a) Indentify the following items in the above tree:
node containing “*”
edge from node containing “-” to node containing “8”
root node
children of the node containing “+”
parent of the node containing “3”
siblings of the node containing “*”
leaf nodes of the tree
subtree who’s root is node contains “+”
path from node containing “+” to node containing “5”
branch from root node to “3”
b) Mark the levels of the tree (level is the number of edges on the path from the root)
c) What is the height (max. level) of the tree?
The binarytree.py file contains the class definitions for BinaryTree and EmptyTree which both implement the
same “binary tree” ADT interface methods. Obviously, the EmptyTree class is only for empty binary trees, but
it is not so obvious that the BinaryTree class is for nonempty trees. A BinaryTree object is basically a “node” in
the binary tree, i.e.,
A BinaryTree object:
_root:
_left:
left subtree
_right:
right subtree
The left subtree (or right subtree) can be either an EmptyTree or a BinaryTree since either type of object respond
to the same “binary tree” ADT interface methods. Having this recursive view of a binary tree eliminates special
cases from the methods. For example, the BinaryTree inorder traversal code is just:
def inorder(self, lyst):
"""Adds items to lyst during an inorder traversal."""
self.getLeft().inorder(lyst)
lyst.append(self.getRoot())
self.getRight().inorder(lyst)
If the left subtree is actually an EmptyTree, then calling its inorder method, i.e.,
def inorder(self, lyst):
return
leaves the lyst unchanged.
Lecture 17 Page 1
Data Structures (CS 1520)
Name:___________________________
/
-
+
9
*
5
8
4
3
2. A traversal iterates through all the nodes in the tree. The four common binary tree traversals are:
Preorder
visit the root node
Preorder traverse left subtree
Preorder traverse right subtree
Inorder
Postorder
Inorder traverse left subtree
visit the root node
Inorder traverse right subtree
Level order
Postorder traverse left subtree
Postorder traverse right subtree
visit the root node
visit nodes at each level from
left-to-right starting with level 0
a. What is the preorder traversal of the above expression tree?
b. What is the inorder traversal of the above expression tree?
c. What is the postorder traversal of the above expression tree?
d. What is the level-order traversal of the above expression tree?
3. Consider the Binary Search Tree (BST). For each node, all values in the left-subtree are < the node and all
values in the right-subtree are > the node.
50
30
70
9
34
18
32
58
80
47
a. Starting at the root, how would you find the node containing “32”?
b. Starting at the root, when would you discover that “65” is not in the BST?
c. Starting at the root, where would be the “easiest” place to add “65”?
d. Where would we add “5” and “33”?
Lecture 17 Page 2
Data Structures (CS 1520)
"""
File: binarytree.py
A binary tree ADT
Example initializations:
anEmptyTree = BinaryTree.THE_EMPTY_TREE
aNonemptyTree = BinaryTree("One item")
"""
from queue import LinkedQueue
class EmptyTree(object):
"""Represents an empty tree."""
# Supported methods
def isEmpty(self):
return True
def __str__(self):
return ""
def __iter__(self):
"""Iterator for the tree."""
return iter([])
def preorder(self, lyst):
return
def inorder(self, lyst):
return
def postorder(self, lyst):
return
# Methods not supported but in the interface for all
# binary trees
def getRoot(self):
raise AttributeError, "Empty tree"
def getLeft(self):
raise AttributeError, "Empty tree"
def getRight(self):
raise AttributeError, "Empty tree"
def setRoot(self, item):
raise AttributeError, "Empty tree"
def setLeft(self, tree):
raise AttributeError, "Empty tree"
def setRight(self, tree):
raise AttributeError, "Empty tree"
def removeLeft(self):
raise AttributeError, "Empty tree"
def removeRight(self):
raise AttributeError, "Empty tree"
Name:___________________________
class BinaryTree(object):
"""Represents a nonemoty binary tree."""
# Singleton for all empty tree objects
THE_EMPTY_TREE = EmptyTree()
def __init__(self, item):
"""Creates a tree with
the given item at the root."""
self._root = item
self._left = BinaryTree.THE_EMPTY_TREE
self._right = BinaryTree.THE_EMPTY_TREE
def isEmpty(self):
return False
def getRoot(self):
return self._root
def getLeft(self):
return self._left
def getRight(self):
return self._right
def setRoot(self, item):
self._root = item
def setLeft(self, tree):
self._left = tree
def setRight(self, tree):
self._right = tree
def removeLeft(self):
left = self._left
self._left = BinaryTree.THE_EMPTY_TREE
return left
def removeRight(self):
right = self._right
self._right = BinaryTree.THE_EMPTY_TREE
return right
def __str__(self):
"""Returns a string representation of the tree
rotated 90 degrees to the left."""
def strHelper(tree, level):
result = ""
if not tree.isEmpty():
result += strHelper(tree.getRight(), level + 1)
result += "| " * level
result += str(tree.getRoot()) + "\n"
result += strHelper(tree.getLeft(), level + 1)
return result
return strHelper(self, 0)
def __iter__(self):
"""Iterator for the tree."""
lyst = []
self.inorder(lyst)
return iter(lyst)
def preorder(self, lyst):
"""Adds items to lyst during
a preorder traversal."""
lyst.append(self.getRoot())
self.getLeft().preorder(lyst)
self.getRight().preorder(lyst)
def inorder(self, lyst):
"""Adds items to lyst during
an inorder traversal."""
self.getLeft().inorder(lyst)
lyst.append(self.getRoot())
self.getRight().inorder(lyst)
def postorder(self, lyst):
"""Adds items to lystduring
a postorder traversal."""
self.getLeft().postorder(lyst)
self.getRight().postorder(lyst)
lyst.append(self.getRoot())
def levelorder(self, lyst):
"""Adds items to lyst during
a levelorder traversal."""
levelsQueue = LinkedQueue()
levelsQueue.enqueue(self)
while not levelsQueue.isEmpty():
node = levelsQueue.dequeue()
lyst.append(node.getRoot())
left = node.getLeft()
right = node.getRight()
if not left.isEmpty():
levelsQueue.enqueue(left)
if not right.isEmpty():
levelsQueue.enqueue(right)
Lecture 17 Page 3
Data Structures (CS 1520)
Name:___________________________
4. Complete the findHelper function of the find method for the BST class.
""" File: bst.py
BST class for binary search trees."""
from queue import LinkedQueue
from binarytree import BinaryTree
A BST object:
class BST(object):
def __init__(self):
self._tree = BinaryTree.THE_EMPTY_TREE
self._size = 0
_size:
def isEmpty(self):
return len(self) == 0
_tree:
def __len__(self):
return self._size
def __str__(self):
return str(self._tree)
def __iter__(self):
return iter(self.inorder())
def inorder(self):
"""Returns a list containing the results of
an inorder traversal."""
lyst = []
self._tree.inorder(lyst)
return lyst
Either an
EmptyTree or
BinaryTree object
def find(self, target):
"""Returns data if target is found or None otherwise."""
def findHelper(tree):
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()
The usage of the “binary tree” ADT interface for both
empty and non-empty trees allows us to easily write
recursive code to implement the add method’s
recursive addHelper function.
# 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
Lecture 17 Page 4