Trees and Binary Search Trees

Slides:



Advertisements
Similar presentations
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 11: Priority Queues and Heaps Java Software Structures: Designing.
Advertisements

Binary Search Tree Smt Genap
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture20.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Chapter 15 Heaps. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define a heap abstract data structure Demonstrate.
1 Heaps and Priority Queues Heap Definition and Operations Using Heaps –Heap sort –Priority queues Implementing heaps –With links –With arrays –Analysis.
A Binary Search Tree Implementation Chapter Chapter Contents Getting Started An Interface for the Binary Search Tree Duplicate Entries Beginning.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
Priority Queues. Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out –The “smallest” element.
1 Introduction to Stacks What is a Stack? Stack implementation using array. Stack implementation using linked list. Applications of Stacks.
Chapter 13 Binary Search Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define a binary search tree abstract.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
Chapter 19 Trees. Chapter Scope Trees as data structures Tree terminology Tree implementations Analyzing tree efficiency Tree traversals Expression trees.
Chapter 9 contd. Binary Search Trees Anshuman Razdan Div of Computing Studies
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.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 9: Trees Java Software Structures: Designing and Using Data.
Binary search trees. What’s on the menu? ADT DictionaryBST & Algorithms SimulatorComplexity.
Chapter 19 Trees. Chapter Scope Trees as data structures Tree terminology Tree implementations Analyzing tree efficiency Tree traversals Expression 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.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
Chapter 10 Trees – part B.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 10: Binary Search Trees Java Software Structures: Designing.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
Trees CSCI Objectives Define trees as data structures Define the terms associated with trees Discuss the possible implementations of trees Analyze.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
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.
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.
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."
1 Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees –Add Element –Remove Element Using.
Chapter 20 Binary Search Trees
COS 312 DAY 25 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 7 Not corrected – 3 MIA Quiz 3 May 4 – Chaps – Available 9 AM - 5 PM – 20 M/C 10.
1 Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees –Add Element –Remove Element Using.
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.
18-1 Chapter 18 Binary Trees Data Structures and Design in Java © Rick Mercer.
1 Binary Search Trees What are the disadvantages of using a linked list? What are the disadvantages of using an array- based list? Binary search trees.
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
The Tree ADT.
The List ADT.
Recursive Objects (Part 4)
Trees Tree nomenclature Implementation strategies Traversals
Trees.
Chapter 21 Heaps and Priority Queues
COMP 103 Binary Search Trees.
Binary Search Trees Why this is a useful data structure. Terminology
Binary Trees Lecture 36 Wed, Apr 21, /21/2018 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.
Java Software Structures: John Lewis & Joseph Chase
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Tree A tree is a data structure in which each node is comprised of some data as well as node pointers to child nodes
ArraySet Methods and ArrayIterator
Heaps and Heap Sorting Heaps implemented in an Array Heap Sorting.
Priority Queues.
Chapter 16 Tree Implementations
Binary Search Trees.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Binary Search Trees A special case of a Binary Tree
CHAPTER 11: Priority Queues and Heaps
CSE 373 Data Structures and Algorithms
CSC 143 Binary Search Trees.
Tree.
Trees.
CMSC 341 Binary Search Trees 8/3/2007 CMSC 341 BST.
Chapter 20 Binary Search Trees
Chapter 21 Heaps and Priority Queues
Presentation transcript:

Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees Add Element Remove Element Using Binary Search Trees: Ordered Lists Reading: L&C 10.1 – 10.9

Using Binary Trees An expression tree has an operation at the root and at each internal node with an operand at each leaf An expression tree is evaluated from the bottom up + Infix Expression (5 - 3) * 4 + 9 Postfix Expression 5 3 – 4 * 9 + * 9 - 4 5 3

Using Binary Trees ExpressionTreeObj class public class ExpressionTreeObj { private int termtype; // node or leaf private char operator; // operator (node) or private int value // operand value (leaf) // constructor public ExpressionTreeObj(int type, char op, int val) // initialize the object attributes (not shown) } // typical accessor methods (also not shown)

Using Binary Trees ExpressionTree class public class ExpressionTree extends LinkedBinaryTree<ExpressionTreeObj> { public ExpressionTree (ExpressionTreeObj element, ExpressionTree leftSubtree, ExpressionTree rightSubtree) super(element, leftSubtree, rightSubtree); } public int evaluateTree() return evaluateNode(root);

Using Binary Trees Postfix tree construction (See L&C Figure 12.11) Assume the postfix expression is 5 3 – 4 * 9 + Create a stack Get 5 -> push(new ExpressionTree(5, null, null) Get 3 -> push(new ExpressionTree(3, null, null) Get - -> op2 = pop() op1 = pop() push(new ExpressionTree(‘-’, op1, op2) Get 4 -> push(new ExpressionTree(4, null, null) Get * -> op2 = pop() push(new ExpressionTree(‘*’, op1, op2) Get 9 -> push(new ExpressionTree(9, null, null) Get + -> op2 = pop() push(new ExpressionTree(‘+’, op1, op2) At end-> pop the completed ExpressionTree

Using Binary Trees Recursive tree evaluation method (my version) private int evaluateNode(BinaryTreeNode<T> root) { if (root != null) { ExpressionTreeObj temp = root.getElement(); if (temp.isOperator()) return computeTerm(temp.getOperator(), evaluateNode(root.getLeft()), evaluateNode(root.getRight())); else return temp.getValue(); } return 0;

Binary Search Tree Definition A binary search tree is a binary tree with the added property that for each node: The left child is less than the parent The parent is less than or equal to the right child Class of objects stored in a binary search tree must implement Comparable interface Now we can define operations to add and remove elements according to search order

Implementing Binary Search Trees <<interface>> BinaryTreeADT<T> <<interface>> BinarySearchTreeADT<T> OR <T extends Comparable<T>> + removeLeftSubtree( ) : void + removeRightSubtree( ) : void + removeAllElements( ) : void + isEmpty( ) : boolean + size( ) : int + contains( ) : boolean + find( ) : T + toString( ) : String + iteratorInOrder( ) : Iterator<T> + iteratorPreOrder( ) : Iterator<T> + iteratorPostOrder( ) : Iterator<T> + iteratorLevelOrder( ) : Iterator<T> + addElement(element : T) : void + removeElement(target : T) : T + removeAllOcurrences (target : T) : void + removeMin() : T + removeMax() : T + findMin( ) : T + findMax( ) : T <<extends>> Note possible addition of extends Comparable<T> to generic specification of <T> for search trees to optionally force a bound on type T Note: toString is missing in L&C Fig 10.2

Implementing Binary Search Trees <<interface>> BinarySearchTreeADT<T> OR <T extends Comparable<T>> <<interface>> BinaryTreeADT<T> <<extends>> <<implements>> <<implements>> LinkedBinarySearchTree <T extends Comparable<T>> LinkedBinaryTree<T> # count : int # root : BinaryTreeNode<T> <<extends>> Note adding the bound of extends Comparable<T> to generic specification of <T> for search trees allows use of compareTo w/o cast BinaryTreeNode<T>

Implementing Binary Search Trees LinkedBinarySearchTree Header public class LinkedBinarySearchTree <T extends Comparable<T>> extends LinkedBinaryTree<T> implements BinarySearchTreeADT<T> Constructors public LinkedBinarySearchTree() { super(); } public LinkedBinarySearchTree(T element) super(element); Why not allow use of the overloaded three argument LinkedBinaryTree constructor?

Implementing Binary Search Trees Semantics for method addElement Add 5 Add 7 Add 3 Add 4 5 5 5 5 7 3 7 3 7 4

Implementing Binary Search Trees LinkedBinarySearchTree method addElement public void addElement(T element) { BinaryTreeNode<T> temp = new BinaryTreeNode<T>(element); if (isEmpty()) // using parent method root = temp; // set parent attribute root else { // need to add to existing tree BinaryTreeNode<T> current = root; boolean added = false;

Implementing Binary Search Trees LinkedBinarySearchTree method addElement while (!added) { // compareTo allowed for <T extends Comparable<T>> if(element.compareTo(current.getElement()) < 0) if (current.getLeft() == null) { current.setLeft(temp); added = true; } else current = current.getLeft();

Implementing Binary Search Trees LinkedBinarySearchTree method addElement if (current.getRight() == null) { current.setRight(temp); added = true; } else current = current.getRight(); count++; // increment parent attribute

Implementing Binary Search Trees Semantics for method removeElement Can’t remove a node by making a reference point around the node being removed Must promote another node to take its place 1. If node has no children, replacement is null 2. If node has only one child, replacement is child 3. If node has two children, replacement is the in-order successor of the node (equal elements are placed to the right)

Implementing Binary Search Trees Semantics for method removeElement Original Tree Remove 3 Remove 5 Remove 10 Rule 1 Rule 2 Rule 3 10 10 10 13 5 15 5 15 7 15 7 15 3 7 13 7 13 13 Note: Corrects error in position of leaf 13 in L&C Figure 10.4

Implementing Binary Search Trees LinkedBinarySearchTree method replacement protected BinaryTreeNode<T> replacement (BinaryTreeNode<T> node) { if (node == null) // paranoid programming? return null; if(node.getLeft() == null && node.getRight() == null) if (node.getLeft() != null && node.getRight() == null) return node.getLeft(); if (node.getLeft() == null && node.getRight() != null) return node.getRight(); // easy cases done - need to work harder now

Implementing Binary Search Trees LinkedBinarySearchTree method replacement BinaryTreeNode<T> current = node.getRight(); BinaryTreeNode<T> parent = node; while (current.getLeft() != null) { parent = current; current = current.getLeft(); } if (current != node.getRight()) parent.setLeft(current.getRight()); current.setRight(node.getRight()); current.setLeft(node.getLeft()); return current;

Using Binary Search Trees: Implementing Ordered Lists BinarySearchTreeList<T> class A List API implemented using a BinarySearchTree Each List method is mapped one-to-one to a method of the LinkedBinarySearchTree<T> class List LinkedBinarySearchTree void add(T element) void addElement(T element) T removeFirst() T removeMin() T removeLast() T removeMax() T remove(T element) T removeElement(T element) T first() T findMin() T last() T findMax() Iterator<T> iterator() {return iteratorInOrder();}

Using Binary Search Trees: Implementing Ordered Lists Analysis of BinarySearchTreeList class Method LinkedList BinarySearchTreeList removeFirst O(1) O(log n) removeLast O(n) O(log n) remove O(n) O(log n) * contains O(n) O(log n) isEmpty/size O(1) O(1) add O(n) O(log n) * * Add and remove may cause tree to become unbalanced, but there is an O(log n) operation to rebalance the tree at the correct point