Lec13BinaryTreesInClass - */ int comp =

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Specification of the Binary Search Tree void add(Class *item) adds the item in such a way that maintains the BST properties 1) must be a binary tree 2) all items in left subtree < node < right subtree for all nodes void remove(Friend *item) bool contains(Friend *item) int size() bool isEmpty() Friend *getItem(Friend *item) We are putting something into this BST. It’s not just anything. It must be something that defined a compare method that compares the appropriate fields of its item. LinkedList class: Link *head Link class: Friend *value, Link *next BinarySearchTree class: Node *root Node class: Friend *value, Node *left, Node *right class BinarySearchTree{ private: Node *root; bool contains(Friend *item, Node *n); public: bool contains(Friend *item); }; bool BinarySearchTree::contains(Friend *item, Node *n) { // check the base case if (n == NULL) return false; /* Now that we have the check above, we don’t need this // this has no children return (n->getValue()->compare(item) == 0);
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: */ int comp = n-&gt;getValue()-&gt;compare(item); switch(comp) { case(-1): return( contains(item, n-&gt;getRight())); case(0): return true; case(1): return( contains(item, n-&gt;getLeft())); } } Algorithmic complexity of contains There are two recursive calls 2^n time? n nodes in the BST, were going to assume it is relatively balanced Each call to contains spawns at most how many more calls to contains? 1 There are at most height calls -&gt; log2n bool BinarySearchTree::contains(Friend *item) { // we want to start at the root node if (root == NULL) return false; else contains(item, root); } void BinarySearchTree::print(FILE *output, Node *n) { // base case if (n == NULL) return; // left print(output, n-&gt;getLeft()); // node n-&gt;printNode(output); // right print(output, n-&gt;getRight()); } void BinarySearchTree::print(FILE *output) { print(output, root); } n nodes in the BST Algorithmic complexity: 2^k (where k is the length of the path) What is 2^log2(n)? n...
View Full Document

Page1 / 2

Lec13BinaryTreesInClass - */ int comp =

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online