 # Binary Search Trees Chapter 6.

## Presentation on theme: "Binary Search Trees Chapter 6."— Presentation transcript:

Binary Search Trees Chapter 6

Implement and use binary search trees in C++ programs.
Objectives You will be able to Implement and use binary search trees in C++ programs. Determine the time complexity of searching binary search trees.

We often need to find a specific item in a collection of items.
Searching We often need to find a specific item in a collection of items. Or determine that it is not present. The simplest strategy is a linear search. Traverse the collection looking for the target item. Time for a linear search is O(n). Grows in proportion to the number of items in the collection, n.

If length of the array is 0, Check the middle item.
Binary Search If an array is ordered, we can make the search much faster by doing a binary search. If length of the array is 0, Search target is not present. Report failure. Check the middle item. If search target is equal Return that item. If the search target is less: Do a binary search of the lower half. If the search target greater Do a binary search of the upper half.

Usually outperforms a linear search Disadvantage:
Binary Search Usually outperforms a linear search Disadvantage: Requires a sequential storage Not appropriate for linked lists (Why?) A linked structure is desirable if we do very much inserting and deleting. It is possible to use a linked structure which can be searched in a binary-like manner.

Binary Search Tree Everything in left subtree is less than root.
49 80 62 35 13 66 28 Everything in left subtree is less than root. Everything in right subtree is greater than root. Recursively!

Tree A data structure which consists of If the tree is nonempty --
a finite set of elements called nodes or vertices. a finite set of directed arcs which connect the nodes. If the tree is nonempty -- One of the nodes (the root) has no incoming arc. Every other node can be reached by following a unique sequence of consecutive arcs starting at the root.

Tree Terminology Root node Children of the parent (3)
Siblings to each other Leaf nodes

Binary Tree Each node has at most two children Examples
Results of multiple coin tosses Encoding/decoding messages in dots and dashes such as Morse code

Implementation A binary tree ADT can be implemented either as a linked structure or as an array.

Array Implementation of Binary Trees
U P E C T M 2 1 6 5 4 3 Store node n in location n of the array.

Array Implementation of Binary Trees
Works OK for complete trees, not for sparse trees

Uses space more efficiently for incomplete trees Provides additional flexibility Each node has two links One to the left child of the node One to the right child of the node If no child node exists for a node, the link is set to NULL

Structural Recursion The subset of a binary tree consisting of any node an all of its descendents is a binary tree. O U P E C T M 2 1 6 5 4 3 Invites the use of recursive algorithms on binary trees.

Recursive Algorithm for Binary Tree Traversal
The "anchor" If the binary tree is empty Do nothing Else N: Visit the Node, process data L: Traverse the left subtree R: Traverse the right subtree The inductive step

Binary Tree Traversal Order
Three possibilities for inductive step … Left subtree, Node, Right subtree Inorder traversal Node, Left subtree, Right subtree the preorder traversal Left subtree, Right subtree, Node the postorder traversal

Binary Search Tree A Collection of Nodes For each node x
Binary Search Tree ADT Binary Search Tree A Collection of Nodes Data Must have <= and == operations Left Child Right Child For each node x value in left child ≤ value in x ≤ value in right child

Determine if BST is empty Search BST for given item
BST Basic Operations Construct an empty BST Determine if BST is empty Search BST for given item Insert a new item in the BST Maintain the BST property Delete an item from the BST Traverse the BST Visit each node exactly once The inorder traversal will visit the values in the nodes in ascending order

Create new empty C++ console application project. Add to project:
Example Create new empty C++ console application project. Add to project: genBST1.h main.cpp

Build and test. main.cpp #include <iostream>
#include "genBST1.h" using namespace std; int main(void) { cout << "This is BST_Demo\n"; cin.get(); return 0; } Build and test.

genBST1.h Copy from Downloads area: This is a subset of Drozdek’s genBST.h template. Figure 6.8, page 221 ff. All textbook examples are available on the author's web site:

BSTNode //************************ genBST1.h ************************** // generic binary search tree #pragma once; template<class T> class BSTNode { public: BSTNode() left = right = 0; } BSTNode(const T& el, BSTNode *l = 0, BSTNode *r = 0) key = el; left = l; right = r; T key; BSTNode *left, *right; };

Class BST template<class T> class BST { public:
BST() {root = 0;} ~BST() {clear();} void clear() // Overloaded clear(root); root = 0; } bool isEmpty() const {return root == 0;} void insert(const T&); T* search(const T& el) const // Overloaded return search(root, el);

Class BST protected: BSTNode<T>* root;
void clear(BSTNode<T>*); T* search(BSTNode<T>*, const T&) const; //void preorder(BSTNode<T>*); //void inorder(BSTNode<T>*); //void postorder(BSTNode<T>*); //virtual void visit(BSTNode<T>* p) { // cout << p->key << ' '; //} };

BST<T>::clear()
template<class T> void BST<T>::clear(BSTNode<T> *p) { if (p != 0) clear(p->left); clear(p->right); delete p; }

BST<T>::insert()
template<class T> void BST<T>::insert(const T& el) { BSTNode<T> *p = root, *prev = 0; // find a place for inserting new node; while (p != 0) prev = p; if (p->key < el) p = p->right; } else p = p->left;

BST<T>::insert()
if (root == 0) // tree is empty; { root = new BSTNode<T>(el); } else if (prev->key < el) prev->right = new BSTNode<T>(el); else prev->left = new BSTNode<T>(el);

BST<T>::search()
template<class T> T* BST<T>::search(BSTNode<T>* p, const T& el) const { while (p != 0) if (el == p->key) return &p->key; } if (el < p->key) p = p->left; else p = p->right; return 0; // el was not found

Test BST Template #include <iostream> #include "genBST1.h"
using namespace std; int main(void) { cout << "This is BST_Demo\n"; BST<int> my_BST; my_BST.insert(13); my_BST.insert(10); my_BST.insert(25); my_BST.insert(2); my_BST.insert(12); my_BST.insert(20); my_BST.insert(31); my_BST.insert(29);

Test BST Template cout << "Items in the tree: ";
for (int i = 0; i < 100; ++i) { int* result = my_BST.search(i); if (result != 0) cout << i << " "; } cout << endl; cin.get(); return 0;

Test Running End of presentation