Chapter 8 Binary Search Trees.

Slides:



Advertisements
Similar presentations
Chapter 8 Binary Search Tree 1 Fall Binary Trees 2 A structure with: i) a unique starting node (the root), in which ii) each node has up to two.
Advertisements

Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
1 Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
Binary Search Trees CS 308 – Data Structures What is a binary tree? Property1: each node can have up to two successor nodes (children) –The predecessor.
1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
EC-211 DATA STRUCTURES LECTURE Tree Data Structure Introduction –The Data Organizations Presented Earlier are Linear in That Items are One After.
1 Chapter 8 Binary Search Trees. 2 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Jake’s Pizza Shop.
trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 19 Binary.
Properties: -Each node has a value -The left subtree contains only values less than the parent node’s value -The right subtree contains only values greater.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Chapter 8 Binary Search Trees. Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Jake’s Pizza Shop.
Binary Search Trees. What is a binary tree? Property 1: each node can have up to two successor nodes.
CS Data Structures Chapter 15 Trees Mehmet H Gunes
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
1 Lecture 11 POLYNOMIALS and Tree sort 2 INTRODUCTION EVALUATING POLYNOMIAL FUNCTIONS Horner’s method Permutation Tree sort.
Binary Trees Chapter Definition And Application Of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two.
CISC220 Fall 2009 James Atlas Lecture 13: Trees. Skip Lists.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
1 5 Linked Structures Based on Levent Akın’s CmpE160 Lecture Slides 3 Binary Trees.
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor.
Chapter 8 Binary Search Trees 1. Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Jake’s Pizza Shop 2.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
Topics Definition and Application of Binary Trees Binary Search Tree Operations.
Week 7 - Friday.  What did we talk about last time?  Trees in general  Binary search trees.
1 Nell Dale Chapter 8 Binary Search Trees Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data.
Computer Science and Software Engineering University of Wisconsin - Platteville 10. Binary Search Tree Yan Shi CS/SE 2630 Lecture Notes Partially adopted.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
1 Binary Trees and Binary Search Trees Based on Dale & Co: Object-Oriented Data Structures using C++ (graphics)
Binary Search Tree. Tree  A nonlinear data structure consisting of nodes, each of which contains data and pointers to other nodes.  Each node has only.
Binary Search Trees … From
Chapter 8 Binary Search Trees. Chapter 8: Binary Search Trees 8.1 – Trees 8.2 – The Logical Level 8.3 – The Application Level 8.4 – The Implementation.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Chapter 11 Binary Trees Dr. Youssef Harrath
Data Structures Using C++ 2E Chapter 11 Binary Trees.
Concepts of Algorithms CSC-244 Unit 19 & 20 Binary Search Tree (BST) Shahid Iqbal Lone Computer College Qassim University K.S.A.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
1 Nell Dale Chapter 8 Binary Search Trees Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Binary Search Trees CS Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
Binary Search Trees Chapter 7 Objectives
Data Structure and Algorithms
Binary Trees and Binary Search Trees
Binary Search Trees Chapter 7 Objectives
Week 6 - Wednesday CS221.
Binary Search Tree (BST)
Lecture 22 Binary Search Trees Chapter 10 of textbook
CMSC 341 Introduction to Trees.
Section 8.1 Trees.
Binary Trees Lecture 36 Wed, Apr 21, /21/2018 Binary Trees.
Data Structures Using C++ 2E
Chapter 20: Binary Trees.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Chapter 21: Binary Trees.
Find in a linked list? first last 7  4  3  8 NULL
Search Sorted Array: Binary Search Linked List: Linear Search
CMSC 341 Binary Search Trees.
Chapter 16 Tree Implementations
CMSC 202 Trees.
CMSC 341 Binary Search Trees.
Chapter 8 Binary Search Tree
Chapter 20: Binary Trees.
Yan Shi CS/SE 2630 Lecture Notes
Trees.
C++ Plus Data Structures
Data Structures Using C++ 2E
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Chapter 8 Binary Search Trees

Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len

A Tree Has a Root Node Owner Jake ROOT NODE Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len

Leaf Nodes have No Children Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len LEAF NODES

A Tree Has Leaves Owner LEVEL 0 Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len LEVEL 0

Level One Owner Jake Manager Chef Brad Carol LEVEL 1 Waitress Waiter Cook Helper Joyce Chris Max Len LEVEL 1

Level Two Owner Jake Manager Chef Brad Carol LEVEL 2 Waitress Waiter Cook Helper Joyce Chris Max Len LEVEL 2

A Subtree Owner Jake Manager Chef Brad Carol LEFT SUBTREE OF ROOT NODE Waitress Waiter Cook Helper Joyce Chris Max Len LEFT SUBTREE OF ROOT NODE

Another Subtree Owner Jake Manager Chef Brad Carol RIGHT SUBTREE Waitress Waiter Cook Helper Joyce Chris Max Len RIGHT SUBTREE OF ROOT NODE

Binary Tree A binary tree is a structure in which: Each node can have at most two children, and in which a unique path exists from the root to every other node. The two children of a node are called the left child and the right child, if they exist.

A Binary Tree V Q L E T A K S

How many leaf nodes? V Q L T E A K S

How many descendants of Q? V Q L T E A K S

How many ancestors of K? Q V T K S A E L

Implementing a Binary Tree with Pointers and Dynamic Data V Q L T E A K S

Node Terminology for a Tree Node

A Binary Search Tree (BST) is . . . A special kind of binary tree in which: 1. Each node contains a distinct data value, 2. The key values in the tree can be compared using “greater than” and “less than”, and 3. The key value of each node in the tree is less than every key value in its right subtree, and greater than every key value in its left subtree.

Shape of a binary search tree . . . Depends on its key values and their order of insertion. Insert the elements ‘J’ ‘E’ ‘F’ ‘T’ ‘A’ in that order. The first value to be inserted is put into the root node. ‘J’

Inserting ‘E’ into the BST Thereafter, each value to be inserted begins by comparing itself to the value in the root node, moving left it is less, or moving right if it is greater. This continues at each level until it can be inserted as a new leaf. ‘J’ ‘E’

Inserting ‘F’ into the BST Begin by comparing ‘F’ to the value in the root node, moving left it is less, or moving right if it is greater. This continues until it can be inserted as a leaf. ‘J’ ‘E’ ‘F’

Inserting ‘T’ into the BST Begin by comparing ‘T’ to the value in the root node, moving left it is less, or moving right if it is greater. This continues until it can be inserted as a leaf. ‘J’ ‘E’ ‘F’ ‘T’

Inserting ‘A’ into the BST Begin by comparing ‘A’ to the value in the root node, moving left it is less, or moving right if it is greater. This continues until it can be inserted as a leaf. ‘J’ ‘E’ ‘F’ ‘T’ ‘A’

What binary search tree . . . is obtained by inserting the elements ‘A’ ‘E’ ‘F’ ‘J’ ‘T’ in that order? ‘A’

the elements ‘A’ ‘E’ ‘F’ ‘J’ ‘T’ in that order. Binary search tree . . . obtained by inserting the elements ‘A’ ‘E’ ‘F’ ‘J’ ‘T’ in that order. ‘A’ ‘E’ ‘F’ ‘J’ ‘T’

Another binary search tree ‘J’ ‘E’ ‘T’ ‘A’ ‘H’ ‘M’ ‘K’ ‘P’ Add nodes containing these values in this order: ‘D’ ‘B’ ‘L’ ‘Q’ ‘S’ ‘V’ ‘Z’

Is ‘F’ in the binary search tree? ‘J’ ‘E’ ‘T’ ‘A’ ‘H’ ‘M’ ‘V’ ‘D’ ‘K’ ‘Z’ ‘P’ ‘B’ ‘L’ ‘Q’ ‘S’

// Assumptions: Relational operators overloaded Class TreeType // Assumptions: Relational operators overloaded class TreeType { public: // Constructor, destructor, copy constructor ... // Overloads assignment // Observer functions // Transformer functions // Iterator pair void Print(std::ofstream& outFile) const; private: TreeNode* root; };

bool TreeType::IsFull() const { NodeType* location; try location = new NodeType; delete location; return false; } catch(std::bad_alloc exception) return true; bool TreeType::IsEmpty() const return root == NULL;

Tree Recursion CountNodes Version 1 if (Left(tree) is NULL) AND (Right(tree) is NULL) return 1 else return CountNodes(Left(tree)) + CountNodes(Right(tree)) + 1 What happens when Left(tree) is NULL?

Tree Recursion CountNodes Version 2 if (Left(tree) is NULL) AND (Right(tree) is NULL) return 1 else if Left(tree) is NULL return CountNodes(Right(tree)) + 1 else if Right(tree) is NULL return CountNodes(Left(tree)) + 1 else return CountNodes(Left(tree)) + CountNodes(Right(tree)) + 1   What happens when the initial tree is NULL?

Tree Recursion Can we simplify this algorithm? CountNodes Version 3 if tree is NULL return 0 else if (Left(tree) is NULL) AND (Right(tree) is NULL) return 1 else if Left(tree) is NULL return CountNodes(Right(tree)) + 1 else if Right(tree) is NULL return CountNodes(Left(tree)) + 1 else return CountNodes(Left(tree)) + CountNodes(Right(tree)) + 1 Can we simplify this algorithm?

Tree Recursion CountNodes Version 4 if tree is NULL return 0 else return CountNodes(Left(tree)) + CountNodes(Right(tree)) + 1 Is that all there is?

// Implementation of Final Version int CountNodes(TreeNode* tree); // Pototype  int TreeType::GetLength() const // Class member function { return CountNodes(root); }   int CountNodes(TreeNode* tree) // Recursive function that counts the nodes if (tree == NULL) return 0; else return CountNodes(tree->left) + CountNodes(tree->right) + 1;

Retrieval Operation

Retrieval Operation void TreeType::GetItem(ItemType& item, bool& found) { Retrieve(root, item, found); }   void Retrieve(TreeNode* tree, ItemType& item, bool& found) if (tree == NULL) found = false; else if (item < tree->info) Retrieve(tree->left, item, found);

Retrieval Operation, cont. else if (item > tree->info) Retrieve(tree->right, item, found); else { item = tree->info; found = true; }

The Insert Operation A new node is always inserted into its appropriate position in the tree as a leaf.

Insertions into a Binary Search Tree

The recursive Insert operation

The tree parameter is a pointer within the tree

Recursive Insert void Insert(TreeNode*& tree, ItemType item) { if (tree == NULL) {// Insertion place found. tree = new TreeNode; tree->right = NULL; tree->left = NULL; tree->info = item; } else if (item < tree->info) Insert(tree->left, item); else Insert(tree->right, item);

Deleting a Leaf Node

Deleting a Node with One Child

Deleting a Node with Two Children

DeleteNode Algorithm if (Left(tree) is NULL) AND (Right(tree) is NULL) Set tree to NULL else if Left(tree) is NULL Set tree to Right(tree) else if Right(tree) is NULL Set tree to Left(tree) else Find predecessor Set Info(tree) to Info(predecessor) Delete predecessor

Code for DeleteNode void DeleteNode(TreeNode*& tree) { ItemType data; TreeNode* tempPtr; tempPtr = tree; if (tree->left == NULL) { tree = tree->right; delete tempPtr; } else if (tree->right == NULL){ tree = tree->left; delete tempPtr;} els{ GetPredecessor(tree->left, data); tree->info = data; Delete(tree->left, data);} }

Definition of Recursive Delete Definition: Removes item from tree Size: The number of nodes in the path from the root to the node to be deleted. Base Case: If item's key matches key in Info(tree), delete node pointed to by tree. General Case: If item < Info(tree), Delete(Left(tree), item); else Delete(Right(tree), item).

Code for Recursive Delete void Delete(TreeNode*& tree, ItemType item) { if (item < tree->info) Delete(tree->left, item); else if (item > tree->info) Delete(tree->right, item); else DeleteNode(tree); // Node found }

Code for GetPredecessor void GetPredecessor(TreeNode* tree, ItemType& data) { while (tree->right != NULL) tree = tree->right; data = tree->info; } Why is the code not recursive?

Printing all the Nodes in Order

Function Print Function Print   Definition: Prints the items in the binary search tree in order from smallest to largest. Size: The number of nodes in the tree whose root is tree Base Case: If tree = NULL, do nothing. General Case: Traverse the left subtree in order. Then print Info(tree). Then traverse the right subtree in order.

Code for Recursive InOrder Print void PrintTree(TreeNode* tree, std::ofstream& outFile) { if (tree != NULL) PrintTree(tree->left, outFile); outFile << tree->info; PrintTree(tree->right, outFile); } Is that all there is?

Destructor void Destroy(TreeNode*& tree); TreeType::~TreeType() { Destroy(root); }   void Destroy(TreeNode*& tree) if (tree != NULL) Destroy(tree->left); Destroy(tree->right); delete tree;

Algorithm for Copying a Tree if (originalTree is NULL) Set copy to NULL else Set Info(copy) to Info(originalTree) Set Left(copy) to Left(originalTree) Set Right(copy) to Right(originalTree)

Code for CopyTree void CopyTree(TreeNode*& copy, const TreeNode* originalTree) { if (originalTree == NULL) copy = NULL; else copy = new TreeNode; copy->info = originalTree->info; CopyTree(copy->left, originalTree->left); CopyTree(copy->right, originalTree->right); }

Inorder(tree) To print in alphabetical order if tree is not NULL Inorder(Left(tree)) Visit Info(tree) Inorder(Right(tree))   To print in alphabetical order

Postorder(tree) Visits leaves first (good for deletion) if tree is not NULL Postorder(Left(tree)) Postorder(Right(tree)) Visit Info(tree)   Visits leaves first (good for deletion)

Preorder(tree) Useful with binary trees (not binary search trees) if tree is not NULL Visit Info(tree) Preorder(Left(tree)) Preorder(Right(tree))   Useful with binary trees (not binary search trees)

Three Tree Traversals

Our Iteration Approach The client program passes the ResetTree and GetNextItem functions a parameter indicating which of the three traversals to use ResetTree generates a queues of node contents in the indicated order GetNextItem processes the node contents from the appropriate queue: inQue, preQue, postQue.

Code for ResetTree void TreeType::ResetTree(OrderType order) // Calls function to create a queue of the tree // elements in the desired order. { switch (order) case PRE_ORDER : PreOrder(root, preQue); break; case IN_ORDER : InOrder(root, inQue); case POST_ORDER: PostOrder(root, postQue); }

Code for GetNextItem ItemType TreeType::GetNextItem(OrderType order,bool& finished) { finished = false; switch (order) case PRE_ORDER : preQue.Dequeue(item); if (preQue.IsEmpty()) finished = true; break; case IN_ORDER : inQue.Dequeue(item); if (inQue.IsEmpty()) case POST_ORDER: postQue.Dequeue(item); if (postQue.IsEmpty()) }

Iterative Versions FindNode Set nodePtr to tree Set parentPtr to NULL Set found to false   while more elements to search AND NOT found if item < Info(nodePtr) Set parentPtr to nodePtr Set nodePtr to Left(nodePtr) else if item > Info(nodePtr) Set nodePtr to Right(nodePtr) else Set found to true

Code for FindNode void FindNode(TreeNode* tree, ItemType item, TreeNode*& nodePtr, TreeNode*& parentPtr) { nodePtr = tree; parentPtr = NULL; bool found = false; while (nodePtr != NULL && !found) { if (item < nodePtr->info) parentPtr = nodePtr; nodePtr = nodePtr->left; } else if (item > nodePtr->info) nodePtr = nodePtr->right; else found = true; Code for FindNode

PutItem Create a node to contain the new item. Find the insertion place. Attach new node. Find the insertion place FindNode(tree, item, nodePtr, parentPtr);

Using function FindNode to find the insertion point

Using function FindNode to find the insertion point

Using function FindNode to find the insertion point

Using function FindNode to find the insertion point

Using function FindNode to find the insertion point

AttachNewNode if item < Info(parentPtr) Set Left(parentPtr) to newNode else Set Right(parentPtr) to newNode

AttachNewNode(revised) if parentPtr equals NULL Set tree to newNode else if item < Info(parentPtr) Set Left(parentPtr) to newNode else Set Right(parentPtr) to newNode

Code for PutItem void TreeType::PutItem(ItemType item) { TreeNode* newNode; TreeNode* nodePtr; TreeNode* parentPtr; newNode = new TreeNode; newNode->info = item; newNode->left = NULL; newNode->right = NULL; FindNode(root, item, nodePtr, parentPtr); if (parentPtr == NULL) root = newNode; else if (item < parentPtr->info) parentPtr->left = newNode; else parentPtr->right = newNode; }

Code for DeleteItem void TreeType::DeleteItem(ItemType item) { TreeNode* nodePtr; TreeNode* parentPtr; FindNode(root, item, nodePtr, parentPtr); if (nodePtr == root) DeleteNode(root); else if (parentPtr->left == nodePtr) DeleteNode(parentPtr->left); else DeleteNode(parentPtr->right); }

PointersnodePtr and parentPtr Are External to the Tree

Pointer parentPtr is External to the Tree, but parentPtr-> left is an Actual Pointer in the Tree

With Array Representation For any node tree.nodes[index] its left child is in tree.nodes[index*2 + 1] right child is in tree.nodes[index*2 + 2] its parent is in tree.nodes[(index – 1)/2].

A Binary Tree and Its Array Representation

Definitions Full Binary Tree: A binary tree in which all of the leaves are on the same level and every nonleaf node has two children

Definitions (cont.) Complete Binary Tree: A binary tree that is either full or full through the next-to-last level, with the leaves on the last level as far to the left as possible

Examples of Different Types of Binary Trees

A Binary Search Tree Stored in an Array with Dummy Values