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.

Slides:



Advertisements
Similar presentations
Chapter 4: Trees Part II - AVL Tree
Advertisements

Binary Search Trees Azhar Maqsood School of Electrical Engineering and Computer Sciences (SEECS-NUST)
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
DictionaryADT and Trees. Overview What is the DictionaryADT? What are trees? Implementing DictionaryADT with binary trees Balanced trees DictionaryADT.
BST Data Structure A BST node contains: A BST contains
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
Chapter 13 Binary Search Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define a binary search tree abstract.
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.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
Sorted Array What is BigO for sorted list implemented as: ArrayList: – Search : – Insert(value) : – Remove(value) : LinkedList: – Search : – Insert(value)
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.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
Lecture 17 Non-Linear data structures Richard Gesick.
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.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
Sets, Maps and Hash Tables. RHS – SOC 2 Sets We have learned that different data struc- tures have different advantages – and drawbacks Choosing the proper.
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
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.
© 2006 Pearson Education Chapter 10: Non-linear Data Structures Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition.
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.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
1 Binary Trees and Binary Search Trees Based on Dale & Co: Object-Oriented Data Structures using C++ (graphics)
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture - 11 on Data Structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Threaded Trees Binary trees have a lot of wasted space: the leaf nodes each.
Binary Search Trees (BST)
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
Hash Tables and Hash Maps. DCS – SWC 2 Hash Tables A Set and a Map are both abstract data types – we need a concrete implemen- tation in order to use.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
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.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Trees By JJ Shepherd. Introduction Last time we discussed searching and sorting in a more efficient way Divide and Conquer – Binary Search – Merge Sort.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
(c) University of Washington20-1 CSC 143 Java Trees.
Topic 2: binary Trees COMP2003J: Data Structures and Algorithms 2
Binary Trees and Binary Search Trees
Recursive Objects (Part 4)
BST Trees
Chapter 16 – Advanced Data Structures
Binary Search Tree (BST)
Trees.
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
Binary Trees.
Chapter 21: Binary Trees.
Lecture 12 CS203 1.
Binary Trees, Binary Search Trees
CSC 143 Java Trees.
Chapter 20: Binary Trees.
Tree.
Trees.
Non-Linear data structures
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Presentation transcript:

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 which allows fast O(log(n)) insertion, deletion and lookup of elements Furthermore, a Tree maintains an ordering of the elements

DCS – SWC 3 Binary Trees A Tree can be perceived as a generali- sation of a Linked List:

DCS – SWC 4 Binary Trees A Tree consists of nodes, which contain data, and references to (up to) n other nodes –n = 1: Linked List –n = 2: Binary Tree If node A refers to node B, we say that –Node A is the parent of node B –Node B is a child of node A

DCS – SWC 5 Binary Trees The node at the top of the tree is called the root node, and does not have a parent The nodes at the edge of the tree are called leaves, and do not have any children Root Leaf

DCS – SWC 6 Binary Trees For a node A, we call the set of nodes consisting of the children of A, and the children of the children of A, and so forth, the descendants of A Descendants of 5

DCS – SWC 7 Binary Search Trees A Binary Tree is thus a special type of Tree, where each node has (up to) 2 children A Binary Search Tree has some additio- nal properties –The data in each node must be of the type Comparable (i.e. implement the interface) –The nodes must obey certain ordering rules

DCS – SWC 8 Binary Search Trees Ordering rules for nodes in a binary search tree: –The data values of all descendants to the left of any node are less than the data value stored in that node –The data values of all descendants to the right of any node are larger than the data value stored in that node –No duplicates allowed

DCS – SWC 9 Binary Search Trees All these nodes are smaller than 10 All these nodes are larger than 10

DCS – SWC 10 Binary Search Trees Searching in a Binary Search Tree is quite fast: O(log(n)) How do we check if a value v is found in the tree? 1.Set current node N = root node 2.If value(N.data) = v, we are done, else If value(N.data) < v, set N = left child (stop if null) If value(N.data) > v, set N = right child (stop if null) 3.Go to 2

DCS – SWC 11 Binary Search Trees public class BinarySearchTree { private Node root; private class Node {...} public BinarySearchTree() {root = null; } public boolean contains(Comparable data) {...} public void add(Comparable data) {...} public void delete(Comparable data) {...} }

DCS – SWC 12 Binary Search Trees // NOTE: Inner class, public instance fields OK private class Node { public Comparable data; public Node left; public Node right; public Node(Comparable data) {...} public boolean contains(Comparable data) {...} public void add(Comparable data) {...} public void delete(Comparable data) {...} }

DCS – SWC 13 Binary Search Trees // BinarySearchTree implementations public boolean contains(Comparable data) { if (root == null) return false; else return root.contains(); } public void add(Comparable data) { if (root == null) root = new Node(data); else root.add(data); } public void delete(Comparable data) {... }

DCS – SWC 14 Binary Search Trees public boolean contains(Comparable v) { if (data.compareTo(v) == 0) return true; Node next; if (data.compareTo(v) < 0) next = left; else next = right; if (next == null) return false; else return (next.contains()); }

DCS – SWC 15 Binary Search Trees We can search a Binary Search Tree in O(log(n)), which is fast However, the condition for this ability is that the tree is always ”sorted”, i.e. obeys the ordering rules Adding or deleting an element must preserve this ordering!

DCS – SWC 16 Binary Search Trees Adding a new element E with value v is done using a recursive algorithm 1.Set current node N = root node 2.If N = null, replace it with E, else 3.If value(N.data) = v, we are done, else If value(N.data) < v, set N = left child If value(N.data) > v, set N = right child 4.Go to 2

DCS – SWC 17 Binary Search Trees public void add(Comparable v) { if (data.compareTo(v) < 0) { if (left == null) left = new Node(v); else left.add(v); } else if (data.compareTo(v) > 0) { if (right == null) right = new Node(v); else right.add(v); }

DCS – SWC 18 Binary Search Trees Deletion is actually the hardest part What happens to the children of some deleted node N? We must handle the cases where N has 0, 1 or 2 children 0 children: Easy. Just find N and delete it. Parent reference (if any) to N must be set to null

DCS – SWC 19 Binary Search Trees N Before After

DCS – SWC 20 Binary Search Trees 1 child: –Fairly easy. Find N and delete it. Parent refe- rence to N must be rerouted to the child of N –Note that if N is the root node, then the child of N becomes the new root node!

DCS – SWC 21 Binary Search Trees N Before After C C Note that C may have children itself…

DCS – SWC 22 Binary Search Trees 2 children: –Complicated… Idea is to move the node with the next larger value in the tree up to take the position of N –Next larger value is found as the leftmost node in the right subtree of N –Keep going left in that subtree, until a node with no left child is found. Call this node L –Replace N with L

DCS – SWC 23 Binary Search Trees Replace N with L –Copy data from L into N (not links!) –Delete original L, following the procedure for deleting a node with zero or a single child (L cannot have a left child) These operations will preserve the ordering properties of the tree

DCS – SWC 24 Tree Traversal The fact that a Binary Search Tree is ordered, make certain tasks quite easy For instance, printing out the content of the tree in sorted order

DCS – SWC 25 Tree Traversal Printing out a tree in sorted order: –Print out the left subtree –Print out data in the root node –Print out the right subtree Again, a highly recursive algorithm…

DCS – SWC 26 Tree Traversal public void printNodes() // Node class { if (left != null) left.printNodes(); System.out.print(data + ” ”); if (right != null) right.printNodes(); }

DCS – SWC 27 Tree Traversal // BinarySearchTree class public void printTree() { if (root != null) root.printNodes(); }

DCS – SWC 28 Tree Traversal

DCS – SWC 29 Tree Traversal This is known as in-order tree traversal: –Apply operation to left subtree –Apply basic operation to root –Apply operation to right subtree

DCS – SWC 30 Tree Traversal We also have pre-order tree traversal: –Apply basic operation to root –Apply operation to left subtree –Apply operation to right subtree

DCS – SWC 31 Tree Traversal

DCS – SWC 32 Tree Traversal And finally post-order tree traversal: –Apply operation to left subtree –Apply operation to right subtree –Apply basic operation to root

DCS – SWC 33 Tree Traversal

DCS – SWC 34 Tree Traversal What tree traversal method to use depends entirely on your application In-order outputs the content of the tree in sorted order Pre- and post-order do not, but are used for other types of algorithms

DCS – SWC 35 Choosing a proper container We have now learned about many types of containers for data Which one is best…? It depends… –Usage scenarios –Data types

DCS – SWC 36 Choosing a proper container Issues in choosing a proper container –How do you access the elements? –Does element order matter? –Which operations must be fast? –Choosing between hash tables and trees (when using sets and maps) –Should I supply a comparator (when using trees)?

DCS – SWC 37 Choosing a proper container How do you access the elements? –If you need access by a key, you should use a map –If you need access by an index, you should use an array or array list –If you only need to check if an element is already present in your container, you can use a set

DCS – SWC 38 Choosing a proper container Does element order matter? –If elements should remain sorted, use a TreeSet –If the order of insertion should be preserved, use a linked list, array or array list –If it does not matter, let other criteria decide your choice

DCS – SWC 39 Choosing a proper container Which operations must be fast? –Add and remove at the end of the container, use a linked list –Looking up a value quickly, use a set or map –If it does not matter, let other criteria decide your choice

DCS – SWC 40 Choosing a proper container Choosing between hash tables and trees (when using sets and maps) If your elements/keys are strings, use a hash table If your elements/keys are defined by yourself, define proper hashCode and equals methods and use hash tables If your elements/keys are defined by someone else, use hash tables if the hashCode and equals methods are properly defined, otherwise use trees

DCS – SWC 41 Choosing a proper container Should I supply a comparator (when using trees)? –If the data type in your tree implements the Comparable interface properly, then no need for further action –If not, you can still use a tree anyway, by supplying a class that implements the Comparator interface, that can compare objects of the type used in the tree

DCS – SWC 42 Exercises Review: R16.15 Programming: P16.17, P16.18 Tip: When implementing a Binary Search Tree class, only implement the methods you actually need. For instance, you pro- bably don’t need the remove method…