Binary Search Trees.

Slides:



Advertisements
Similar presentations
Computer Science C++ High School Level By Guillermo Moreno.
Advertisements

1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 10 Ming Li Department of.
Building Java Programs Binary Search Trees reading: 17.3 – 17.4.
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
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.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
Building Java Programs Chapter 17 Binary Trees. 2 Creative use of arrays/links Some data structures (such as hash tables and binary trees) are built around.
Building Java Programs Binary Search Trees; TreeSet.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets read slides created by Marty Stepp and Hélène Martin
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
BINARY SEARCH TREE. Binary Trees A binary tree is a tree in which no node can have more than two children. In this case we can keep direct links to the.
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 12 – Data Structures – Trees Sorting Algorithms.
Binary Search Trees Nilanjan Banerjee. 2 Goal of today’s lecture Learn about Binary Search Trees Discuss the first midterm.
Topic 19 Binary Search Trees "Yes. Shrubberies are my trade. I am a shrubber. My name is 'Roger the Shrubber'. I arrange, design, and sell shrubberies."
CS261 Data Structures Binary Search Trees II Bag Implementation.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
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.
CSE 143 Lecture 22 Binary Search Trees continued; Tree Sets read slides adapted from Marty Stepp and Hélène Martin
CSE 143 Lecture 21 Binary Search Trees, continued read slides created by Marty Stepp
Trees 3 The Binary Search Tree Section 4.3. Binary Search Tree Also known as Totally Ordered Tree Definition: A binary tree B is called a binary search.
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 (BST)
CS 261 – Fall 2009 Binary Search Trees. Can we do something useful? How can we make a collection using the idea of a binary tree? How about starting with.
CMSC 341 Binary Search Trees. 8/3/2007 UMBC CMSC 341 BST 2 Binary Search Tree A Binary Search Tree is a Binary Tree in which, at every node v, the values.
CSE 143 Lecture 20 Binary Search Trees read 17.3 slides created by Marty Stepp
1 Nell Dale Chapter 8 Binary Search Trees Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
BSTs, AVL Trees and Heaps Ezgi Shenqi Bran. What to know about Trees? Height of a tree Length of the longest path from root to a leaf Height of an empty.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets
CSE 373 Binary search trees; tree height and balance
BST Trees
Binary search tree. Removing a node
Binary Trees "The best time to plant a tree is twenty years ago. The second best time is now." -Chinese proverb Real programmmers always confuse Christmas.
Trees.
Binary Search Trees -Monty Python and The Holy Grail
ITEC 2620M Introduction to Data Structures
Topic 18 Binary Search Trees
Tree data structure.
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.
Building Java Programs
Topic 19 Binary Search Trees
Building Java Programs Chapter 17
Rick Mercer, Allison Obourn, Marty Stepp
Chapter 21: Binary Trees.
Building Java Programs
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
Binary Search Tree AVL Tree
Tree data structure.
Search Sorted Array: Binary Search Linked List: Linear Search
CSE 373: Data Structures and Algorithms
CSE 143 Lecture 20 Binary Search Trees, continued read 17.3
Building Java Programs
Building Java Programs
Binary Search Trees continued; Tree Sets
Lecture 21: Binary Search Trees; TreeSet
CSE 373 Data Structures and Algorithms
CSC 143 Binary Search Trees.
Building Java Programs
Lecture 21: Binary Search Trees; TreeSet
Yan Shi CS/SE 2630 Lecture Notes
Trees.
CS 261 – Data Structures Binary Search Trees.
Trees Trees.
Binary Search Trees CS 580U Fall 17.
Presentation transcript:

Binary Search Trees

Why Use Trees? AKA what's wrong with linked lists? Accessing an item in a linked list takes O(N) time in average and worst case Binary trees can improve on this – reduce access time to O(logN) in average case Expands on the idea of binary search and allows insertions and deletions Worst case degenerates to O(N) but this can be avoided by using balanced trees

Binary Search Trees binary search tree: a binary tree in which every node's left subtree holds values less than the node's value, and its right subtree holds values greater than the node's value The left and right subtrees of a BST are also BSTs. Elements are stored in sorted order 25 17 34

BST Insertion Add the following values one at a time to an initially empty BST. 84 20 7 94 9 23 1 What does the tree look like?

Traversals What happens in an in-order traversal of a binary search tree?

Question After adding N distinct values in random order to a BST what is the expected height of the tree? A. O(N1/2) B. O(logN) C. O(N) D. O(NlogN) E. O(N2)

Question After adding N distinct values to a BST what is the worst case height of the tree? A. O(N1/2) B. O(logN) C. O(N) D. O(NlogN) E. O(N2)

Example Insert the elements below into an initially empty BST: 3 5 6 8 10 11 14 18 What is the height of the tree?

BST class // Interface (BST.h) #ifndef _BST_H #define _BST_H // include TreeNode struct class BST { public: BST(); ~BST(); void add(int value); int getMin() const; bool isEmpty() const; void print() const; bool contains(int value) const; void remove(int value); private: TreeNode* root; bool contains(TreeNode* node, int value) const; void print(TreeNode* node) const; void add(TreeNode* node, int value); }; #endif

add Method Add a new value to the BST so that the resulting tree is also a BST Where do we add 7? 14? 39? Typical approach for recursive tree method: member function that calls helper only private helper member function: takes same args plus a node pointer 25 15 45 8 23 33 58 13

BST Implementation BST:BST() { root = NULL; } void BST::add(int value) { add(root, value); void BST::add(TreeNode* node, int value) { if(node == NULL) node = new TreeNode(value); else if(value < nodedata) add(nodeleft, value); else if(value > nodedata) add(noderight, value); Oops: modifying the NULL pointer doesn't change the tree How do we make the base case work? Setting node modifies local variable, but doesn't modify existing tree. Need to modify the root Or modify an existing node's left or right pointer

add Method: What's Wrong? void BST::add(int value) { add(root, value); } void BST::add(TreeNode* node, int value) { if(node == NULL) node = new TreeNode(value); else if(value < nodedata) add(nodeleft, value); else if(value > nodedata) add(noderight, value); call tree.add(24) 25 15 45 8 23 33 58 24 13 node

BST Implementation void BST::add(int value) { if(root == NULL) root = new TreeNode(value); else add(root, value); } void BST::add(TreeNode* node, int value) { // private if(value < nodedata){ if(nodeleft == NULL) nodeleft = new TreeNode(value); else add(nodeleft, value); else if(value > nodedata){ if(noderight == NULL)noderight = new TreeNode(value); else add(noderight, value); We addressed this type of issue in linked lists

BST Implementation void BST::add(int value) { add(root, value); } void BST::add(TreeNode*& node, int value) { if(node == NULL) node = new TreeNode(value); else if(value < nodedata) add(nodeleft, value); else if(value > nodedata) add(noderight, value); How do we make the base case work? Pass the current node pointer by reference for changes to affect tree Recall: The difference in a regular parameter and a reference parameter

add Method: Second Approach void BST::add(int value) { add(root, value); } void BST::add(TreeNode*& node, int value) { if(node == NULL) node = new TreeNode(value); else if(value < nodedata) add(nodeleft, value); else if(value > nodedata) add(noderight, value); call tree.add(24) We wanted to modify a pointer in the tree- So pass the pointer by reference 25 15 45 8 23 33 58 node 24 13

getMin Method getMin returns smallest value in binary search tree throws exception if tree is empty

getMin Method getMin returns the minimum value in the binary search tree throws exception if tree is empty /* Returns minimum value in BST. If BST is empty, throws a string exception. */ int BST::getMin() const { if(root == NULL) throw "Cannot get minimum in empty BST"; return getMin(root); } // Add helper to .h file int BST::getMin(TreeNode* node) const { // private helper method if(node  left == NULL) return nodedata; else return getMin(node  left);

contains Method contains(value): returns true if value is in binary search tree, and false otherwise Like many tree methods, requires a private helper method that takes a node pointer as an additional argument Exercise: Write the contains Method

remove Method remove: BST member function Removes specified integer from BST (if it's in the tree) Removal must result in a BST

remove Method tree.remove(33) tree.remove(8) tree.remove(45) 25 15 45 23 33 58 13

Removal remove a leaf: replace with NULL remove node with left child only: replace with left child remove node with right child only: replace with right child remove node with two children: replace with min from right subtree Could also replace with max from left subtree 55 50 tree.remove(50); 30 60 30 60 21 42 80 21 42 55 80

remove Method Method removes the specified value from the BST if it is present void BST::remove(int value) { remove(root, value); // call helper on root of tree } // Need to modify tree – pass node pointer by reference void BST::remove(TreeNode*& node, int value){

remove Helper // right child only case void BST::remove(TreeNode*& node, int value){ if(node == NULL) { // value isn't in tree } else if(value < nodedata) remove(nodeleft, value); else if(value > nodedata) remove(noderight, value); else { // nodedata == value, remove this node. TreeNode* delNode = NULL; if(nodeleft == NULL && noderight == NULL) { // leaf case delNode = node; node = NULL; else if(noderight == NULL) { // left child only case node = nodeleft; else if(nodeleft == NULL) { // right child only case delNode = node; node = noderight; } else { //case: left and right subtrees. nodedata = getMin(noderight); int minVal = nodedata; remove(noderight, minVal); if(delNode != NULL) delete delNode;

Destructor Delete all nodes

Destructor Delete all nodes BST::~BST() { destroy(root); } void BST::destroy(TreeNode* node) { if(node != NULL) { destroy(node->left); destroy(node->right); delete node;