Download presentation

Presentation is loading. Please wait.

1
Binary Search Trees Chapter 6

2
**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.

3
**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.

4
**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.

5
**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.

6
**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!

7
**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.

8
**Tree Terminology Root node Children of the parent (3)**

Siblings to each other Leaf nodes

9
**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

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

11
**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.

12
**Array Implementation of Binary Trees**

Works OK for complete trees, not for sparse trees

13
**Linked Implementation of Binary 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

14
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.

15
**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

16
**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

17
**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

18
**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

19
**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

20
**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.

21
**Copy from Downloads area:**

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:

22
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; };

23
**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);

24
**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 << ' '; //} };

25
**BST<T>::clear()**

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

26
**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;

27
**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);

28
**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

29
**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);

30
**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;

31
Test Running End of presentation

Similar presentations

© 2021 SlidePlayer.com Inc.

All rights reserved.

To make this website work, we log user data and share it with processors. To use this website, you must agree to our Privacy Policy, including cookie policy.

Ads by Google