AITI Lecture 20 Trees, Binary Search Trees Adapted from MIT Course 1.00 Spring 2003 Lecture 28 and Tutorial Note 10 (Teachers: Please do not erase the.

Slides:



Advertisements
Similar presentations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Advertisements

SUNY Oneonta Data Structures and Algorithms Visualization Teaching Materials Generation Group Binary Search Tree A running demonstration of binary search.
Search Trees: BSTs and B-Trees David Kauchak cs302 Spring 2013.
Binary Trees. DCS – SWC 2 Binary Trees Sets and Maps in Java are also available in tree-based implementations A Tree is – in this context – a data structure.
Introduction to Computation and Problem Solving Class 28: Binary Search Trees Prof. Steven R. Lerman and Dr. V. Judson Harward.
Balanced Search Trees. 2-3 Trees Trees Red-Black Trees AVL Trees.
A balanced life is a prefect life.
DictionaryADT and Trees. Overview What is the DictionaryADT? What are trees? Implementing DictionaryADT with binary trees Balanced trees DictionaryADT.
Binary Search Trees Briana B. Morrison Adapted from Alan Eugenio.
Data Structures: Trees i206 Fall 2010 John Chuang Some slides adapted from Marti Hearst, Brian Hayes, or Glenn Brookshear.
Department of Computer Science University of Maryland, College Park
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
6/14/2015 6:48 AM(2,4) Trees /14/2015 6:48 AM(2,4) Trees2 Outline and Reading Multi-way search tree (§3.3.1) Definition Search (2,4)
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
Binary Search Trees1 ADT for Map: Map stores elements (entries) so that they can be located quickly using keys. Each element (entry) is a key-value pair.
© 2004 Goodrich, Tamassia (2,4) Trees
Chapter 13 Binary Search Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define a binary search tree abstract.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
General Trees and Variants CPSC 335. General Trees and transformation to binary trees B-tree variants: B*, B+, prefix B+ 2-4, Horizontal-vertical, Red-black.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
By : Budi Arifitama Pertemuan ke Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation.
CPSC 335 BTrees Dr. Marina Gavrilova Computer Science University of Calgary Canada.
Types of Binary Trees Introduction. Types of Binary Trees There are several types of binary trees possible each with its own properties. Few important.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Binary SearchTrees [CLRS] – Chap 12. What is a binary tree ? A binary tree is a linked data structure in which each node is an object that contains following.
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
Binary Search Tree Traversal Methods. How are they different from Binary Trees?  In computer science, a binary tree is a tree data structure in which.
© 2004 Goodrich, Tamassia Binary Search Trees1 CSC 212 Lecture 18: Binary and AVL Trees.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
CS 206 Introduction to Computer Science II 02 / 13 / 2009 Instructor: Michael Eckmann.
Lecture1 introductions and Tree Data Structures 11/12/20151.
Fall 2006 CSC311: Data Structures 1 Chapter 10: Search Trees Objectives: Binary Search Trees: Search, update, and implementation AVL Trees: Properties.
© 2004 Goodrich, Tamassia Trees
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
AVL Trees An AVL tree is a binary search tree with a balance condition. AVL is named for its inventors: Adel’son-Vel’skii and Landis AVL tree approximates.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
1 Lecture 21: Binary Search Tree delete etc. operations Lecturer: Santokh Singh CompSci 105 SS 2005 Principles of Computer Science.
Binary Search Trees (BST)
Data Structures Using C++ 2E Chapter 11 Binary Trees.
CS 367 Introduction to Data Structures Lecture 8.
CSE 2331/5331 Topic 8: Binary Search Tree Data structure Operations.
Chapter 10 Trees © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
Balanced Search Trees 2-3 Trees AVL Trees Red-Black Trees
Binary Search Tree (BST)
Chapter 10.1 Binary Search Trees
Lecture 22 Binary Search Trees Chapter 10 of textbook
Trees.
i206: Lecture 13: Recursion, continued Trees
Binary Tree and General Tree
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Binary Search Trees.
AVL Trees CENG 213 Data Structures.
(2,4) Trees (2,4) Trees (2,4) Trees.
Lecture 12 CS203 1.
Binary Search Trees.
(2,4) Trees 2/15/2019 (2,4) Trees (2,4) Trees.
(2,4) Trees (2,4) Trees (2,4) Trees.
CSC 143 Binary Search Trees.
Trees.
Presentation transcript:

AITI Lecture 20 Trees, Binary Search Trees Adapted from MIT Course 1.00 Spring 2003 Lecture 28 and Tutorial Note 10 (Teachers: Please do not erase the above note)

Binary Search Trees We define the concept of binary search tree as a binary tree of nodes containing an ordered key with the following additional property. The left subtree of every node (if it exists) must only contain nodes with keys less than or equal to the parent and the right subtree (if it exists) must only contain nodes with keys greater than or equal to the parent.

Goals We are going to implement a binary search tree with the usual data structure operations and then critique the implementation. Generalizations of the binary search tree drive many important applications, including commercial databases. The implementation will give you a feel for tree methods that tend to be more "visual" or "topological" than array or list implementations.

Binary tree example g bx dwz v root c

Implementing a Binary Tree We’ll build a Tree class: –One data member: root –One constructor: Tree() –Methods: insert: build a tree, node by node inorder traversal postorder traversal (we omit preorder)

Implementing, p.2 We also build a Node inner class: –Three data members: data, left, right –Three methods, all used by corresponding methods in the Tree class: insertNode traverseInorder traversePostorder –Methods are invoked on root node and then traverse the tree as needed

Exercise 1 Draw the tree that results from: public class TreeMain { public static void main(String[] args) { Tree z= new Tree(); z.insert("b"); z.insert("q"); z.insert("t"); z.insert("d"); z.insert("a"); // Four more lines to appear in exercise 2 }

Solution b aq dt

Exercise 2 What is the output if main() then contains the following 4 lines? System.out.println("Inorder"); z.inorder(); System.out.println("Postorder"); z.postorder(); Inorder is: –traverse left, visit (print) current, traverse right Postorder is: –Traverse left, traverse right, visit (print) current

Solution Inorder: –a b d q t Postorder: –a d t q b

Tree class class Tree { private Node root; public Tree() { root= null; } public void inorder() { if (root != null) root.traverseInorder(root); } public void postorder() { if (root != null) root.traversePostorder(root); } public void insert(Comparable o) { Node t= new Node(o); if (root==null) root= t; else root.insertNode(t); }

Node class: data, constructor private class Node { public Comparable data; public Node left; public Node right; public Node(Comparable o) { data= o; left= null; right= null; }

Node class, insertNode public void insertNode(Node n) { if (n.data.compareTo(data) < 0) { if (left==null) left= n; else left.insertNode(n); } else { if (right == null) right= n; else right.insertNode(n); }

insert() in Action insert(20) null parent at end of failed search 20 new node 8

Exercise 3: traversal Write the two traversal methods in Node: public void traverseInorder( Node n) { if ( n != null ) { // Traverse left subtree // Print current Node // Traverse right subtree } public void traversePostorder( Node n) { if ( n != null ) { // Traverse left subtree // Traverse right subtree // Print current Node }

Solution public void traverseInorder( Node n) { if ( n != null ) { traverseInorder( n.left); System.out.println( n.data); traverseInorder( n.right); } public void traversePostorder( Node n) { if ( n != null ) { traversePostorder( n.left); traversePostorder( n.right); System.out.println( n.data); }

Exercise 4: Find Node This is very similar to insertNode: –In class Tree, add: public boolean find(Comparable o) { if (root== null) return false; else return root.findNode(o); } –In class Node, add: public boolean findNode(Comparable o) { if (o.compareTo(data) < 0) { // Add code here } else if (o.compareTo(data) > 0) { // Add code here } else // Equal return true; return false; } // Never reached

find() in Action st iteration 2 nd iteration find(19) 8

Solution public boolean findNode(Comparable o) { if (o.compareTo(data) < 0) { if (left== null) return false; else left.findNode(o); } else if (o.compareTo(data) > 0) { if (right == null) return false; else right.findNode(o); } else // Equal return true; return false; // Never reached }

Keys and Values If binary search trees are ordered, then they must be ordered on some key possessed by every tree node. A node might contain nothing but the key, but it's often useful to allow each node to contain a key and a value. The key is used to look up the node. The value is extra data contained in the node indexed by the key.

Maps Such data structures with key/value pairs are usually called maps. As an example, consider the entries in a phone book as they might be entered in a binary search tree. The subscriber name, last name first, serves as the key, and the phone number serves as the value.

Key and Value Type Sometimes you may not need the value. But if one node has a value, you probably want to supply one for every node. We also haven't specified the type of the key and value. They can be of any class you want, but all nodes should possess keys that are instances of the same class and values that are instances of the same class. Keys and values do not have to be the same type. Keys and values will be handled as Object s by our tree implementation except when we need to compare them.

Duplicate Keys Do we allow the tree to contain nodes with identical keys? There is nothing in the concept of a binary search tree that prevents duplicate keys. In the interface that we will implement, we use the keys to access the values. If we allowed duplicate keys, we wouldn't be able to distinguish between multiple nodes possessing the same key. Thus, in this implementation, duplicate keys will not be allowed. Duplicate values associated with different keys are legal.

Maps Implementing tree structures with keys and values is a straightforward extension to what we just did. The Node contains: –Key –Value –Left –Right

The Efficiency of Binary Search It makes intuitive sense that the basic operations on a binary search tree should require O(h) time where h is the height of the tree. It turns out that the height of a balanced binary tree is roughly log 2 (n) where n is the number of elements if the tree remains approximately balanced. It can be proved that if keys are randomly inserted in a binary search tree, this condition will be met, and the tree will remain adequately enough balanced so that search and insertion time will approximate O(log n).

Tree Balance There are some extremely simple and common cases, however, where keys will not be inserted in random order. Consider what will happen if you insert keys into a search tree from a sorted list. The tree will assume a degenerate form equivalent to the source list and search and insertion times will degrade to O(n). There are many variants of trees, e.g., red-black trees, AVL trees, B-trees, that try to solve this problem by rebalancing the tree after operations that unbalance it.

Keys Inserted in Order

delete() Strategy The last slides show what happens to delete nodes from a tree. It’s messy, and we cover it only in overview form. When we delete a node from a binary search tree, we must ensure that the resulting structure (1) is still a tree, and (2) the tree still obeys the rule of a binary search tree. The rule requires that for every node, the keys in the left subtree if present precede the key of the node which must precede the keys in the right subtree.

delete() Cases, 1 There are three deletion cases we must consider: 1.The deleted node has no children, e.g., node 29 below. 2.The deleted node has one child, e.g., node 7 below. 3.The deleted node has two children, e.g., node 25 below

delete(), No Children

delete(), 1 Child

delete(), 2 Children

delete(), 2 Children Strategy In the last case, that of two children, the problem is more serious since the tree is now in three parts. The solution starts by realizing that we can minimize the ordering problem by stitching the tree back together using the node immediately preceding or following the deleted node in inorder sequence. These are known as the predecessor and successor nodes.

Using the Successor Node Let's choose the successor node. The successor of a node with a right subtree will be the first node of that subtree. If we replace the deleted node by its successor, then all ordering conditions will be met. But what about the successor's children. The successor of a node with two children can have at most one child (a right child). If it had a left subtree, the node couldn't be the successor since members of the left subtree follow the deleted node but precede the successor. Since the successor can have at most one subtree, we can move the successor up to replace the node we want to remove and relink its right subtree, if present, as in the second case above.

delete(), find successor first of right subtree

delete(), replace successor

delete(), replace successor

delete(), replace successor