SlideShare a Scribd company logo
1 of 19
Download to read offline
Binary Search Trees 
Christopher Simpkins 
chris.simpkins@gatech.edu 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 1 / 19
Trees are everywhere. 
1 
1Source:http://commons.wikimedia.org/wiki/File: 
Winnersh_Meadows_Trees.jpg 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 2 / 19
They’re in our web browsers. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 3 / 19
They’re in our file systems. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 4 / 19
They’re even in pop culture. 
2 
2Source: 
http://userserve-ak.last.fm/serve/500/44019065/Neon+Trees.png 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 5 / 19
But they’re not in Kansas. 
3 
3Source: 
http://en.wikipedia.org/wiki/File:Wabaunsee_County_View.JPG 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 6 / 19
Binary Tree Nodes 
The nodes of a binary tree have 
a data item, 
a link to a left node, and 
a link to a right node. 
private class Node<E> { 
E item; 
Node<E> left; 
Node<E> right; 
Node(E item, Node<E> left, Node<E> right) { 
this.item = item; 
this.left = left; 
this.right = right; 
} 
} 
Just as in the other linked data structures we’ve studied, binary trees 
are recursive. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 7 / 19
Binary Tree Structure 
Every tree has a distinguished root node with no parent. 
All other nodes have exactly one parent. 
Nodes which have no children are called leaf nodes. 
Nodes which have children are called interior nodes. 
Every node has 0, 1, or 2 children. 
Every node can be reached by a unique path from the root node. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 8 / 19
Binary Search Trees 
A binary search tree (BST) is a binary tree in which for any node, 
all the elements in the node’s left subtree are less than the node’s 
data item, and 
all the elements in the node’s right subtree are equal to or greater 
than the node’s data item. 
A BST is distinguished by this property, but it’s ADT is simple: add 
elements, find element’s in the tree, and iterate over the elements in a 
tree. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 9 / 19
Maintaining The BST Property 
To add a new value to binary tree and maintain the BST property, we 
insert new nodes for data items into the left subtree of a node if 
the new item is less than the node’s item, or 
the right subtree otherwise. 
Every new item creates a leaf node, which can later become an interior 
node after additional items have been added. Here’s the structure of a 
BST after adding the sequence of numbers 3, 4, 1, 5, 2: 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 10 / 19
The Path to an Item 
To find a path to an item in a BST: , then 
set the path to the empy list 
set the root node as the currentNode 
until we find the node containing the item or exhaust the BST: 
if currentNode contains the item, add it to the path and return it 
else if query item is less than the item in currentNode, add 
currentNode to path and set the left child as the new currentNode 
else add add currentNode to path and set the right child as the new 
currentNode 
if the item wasn’t found, set the path to the empty list 
See public List<E> path(E queryItem) in 
BinarySearchTree.java for the code. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 11 / 19
Traversing a Binary Tree 
There are three primary ways to traverse a binary tree: 
Pre-order: 
Process node’s item. 
Process left subtree. 
Process right subtree. 
In-order: 
Process left subtree. 
Process node’s item. 
Process right subtree. 
Post-order: 
Process left subtree. 
Process right subtree. 
Process node’s item. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 12 / 19
Simple In-Order Traversal 
The code for in-order traversal follows the recursive structure of the 
tree: 
public void printInOrder() { 
printInOrder(root); 
} 
private void printInOrder(Node<E> node) { 
if (node != null) { 
printInOrder(node.left); 
System.out.print(node.item + " "); 
printInOrder(node.right); 
} 
} 
The code above prints the elements in ascending order. Let’s add a 
printDescending() method to BinarySearchTree.java. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 13 / 19
Recursively Building a Result: inOrderList() 
We can use the recursive accumulator idiom to collect the elements of 
the tree in an in-order traversal: 
public List<E> toList() { 
return inOrderList(root, new ArrayList<E>()); 
} 
private List<E> inOrderList(Node<E> node, List<E> accum) { 
if (null == node) { 
return accum; 
} else { 
inOrderList(node.left, accum); 
accum.add(node.item); 
inOrderList(node.right, accum); 
} 
return accum; 
} 
Again, the code follows the recursive structure of the tree. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 14 / 19
Imperative traveral: inOrderImperative() 
Contrast the previous code for getting an in-order list of BST elements 
with an imperative version: 
public List<E> inOrderImperative() { 
Node<E> curNode = root; 
Stack<Node<E>> fringe = new LinkedStack<>(); 
List<E> accum = new ArrayList<E>(); 
while ((curNode != null) || !fringe.isEmpty()) { 
while (curNode != null) { 
fringe.push(curNode); 
curNode = curNode.left; 
} 
curNode = fringe.pop(); 
accum.add(curNode.item); 
curNode = curNode.right; 
} 
return accum; 
} 
We need extra bookkeeping variables to keep track of where we are in 
the tree so we can back-track. See BinarySearchTree.java for 
comments explaining the algorithm. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 15 / 19
Iterators 
Iterators can free clients from having to implement traversal 
algorithms. We can even plug our data structures into Java’s for-each 
loop by implementing java.lang.Iterable: 
public interface Iterable<T> { 
java.util.Iterator<T> iterator(); 
} 
As a reminder, java.util.Iterator: 
public interface Iterator<E> { 
boolean hasNext(); 
E next(); 
void remove(); 
} 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 16 / 19
Stateful In-Order Tree Traversal 
In the traversal examples we saw earlier the traversal order was 
effected by the method call stack. A stateful iterator is much more 
challenging because: 
The iterator must remember where it is in the tree 
The iterator must be able to back-track to parent nodes after 
processing child branches 
The essential implementation idea is to use a stack to store nodes for 
back-tracking. Traditionally (at least in AI), this “to-do list” stack is 
called the fringe4. 
Let’s look at BinarySearchTree.java again to see how we implement a 
stateful in-order iterator. 
4This search strategy is called depth-first search. Using a queue for the fringe 
instead of a stack would effect a breadth-first search 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 17 / 19
Programming Exercise 1 
Add a toString method to BinarySearchTree. 
The string should have a left square bracket, followed by the 
elements in the BST in-oder separated by spaces, followed by a 
right square bracket. For example, [1 2 3 4 ] 
If the BST is empty, the string should contain empty square 
barckets, e.g., []. 
Your toString method should use a recursive helper method, similar 
to inOrderList. Your helper method should use a StringBuilder 
for its accumulator. 5 
5StringBuilder works just like StringBuffer. What’s the difference? 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 18 / 19
Programming Exercise 2 
Recall the method that adds nodes to the BinarySearchTree: 
private Node<E> insert(E newItem, Node<E> node) { 
if (node == null) { 
return new Node<E>(newItem, null, null); 
} else if (newItem.compareTo(node.item) < 0) { 
node.left = insert(newItem, node.left); 
return node; 
} else { 
node.right = insert(newItem, node.right); 
return node; 
} 
} 
Notice that this implementation allows duplicate items. Modify this 
method so that BinarySearchTree is a set, that is, does not insert 
duplicate items. 
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 19 / 19

More Related Content

What's hot

Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its FundamentalsHitesh Mohapatra
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary treeZaid Shabbir
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)swajahatr
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureRai University
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using Ccpjcollege
 

What's hot (20)

Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
Chapter 11 ds
Chapter 11 dsChapter 11 ds
Chapter 11 ds
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
Data structure-question-bank
Data structure-question-bankData structure-question-bank
Data structure-question-bank
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
Data structures
Data structuresData structures
Data structures
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
Linked list
Linked listLinked list
Linked list
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Review session2
Review session2Review session2
Review session2
 
Data structures
Data structuresData structures
Data structures
 
Datastructure
DatastructureDatastructure
Datastructure
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
Data Structure Basics
Data Structure BasicsData Structure Basics
Data Structure Basics
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using C
 

Viewers also liked

Los 4 pilares de la educación
Los 4 pilares de la educaciónLos 4 pilares de la educación
Los 4 pilares de la educacióngonzalo maqueda
 
Памятные даты Архангельской области 2014
Памятные даты Архангельской области 2014Памятные даты Архангельской области 2014
Памятные даты Архангельской области 2014patriot29
 
Asti Aircraft Service REFERENCE LETTER
Asti Aircraft Service REFERENCE LETTERAsti Aircraft Service REFERENCE LETTER
Asti Aircraft Service REFERENCE LETTERCarlotta Marsella
 
The Pearl Marrakech VH MAG
The Pearl Marrakech VH MAGThe Pearl Marrakech VH MAG
The Pearl Marrakech VH MAGAlia Beskok
 
Chris Box letter[1].PDF
Chris Box letter[1].PDFChris Box letter[1].PDF
Chris Box letter[1].PDFDale Vaughan
 
What have you learnt about technologies
What have you learnt about technologiesWhat have you learnt about technologies
What have you learnt about technologiestaraleggett
 
Carta appartenenza + scheda genitore
Carta appartenenza + scheda genitoreCarta appartenenza + scheda genitore
Carta appartenenza + scheda genitoreChiarabaldini
 
Iberdrola lidera la clasificación de las compañías eléctricas europeas
Iberdrola lidera la clasificación de las compañías eléctricas europeasIberdrola lidera la clasificación de las compañías eléctricas europeas
Iberdrola lidera la clasificación de las compañías eléctricas europeasEl_Blog_De_La_Energia
 
Presentacion de un blog
Presentacion de un blogPresentacion de un blog
Presentacion de un blogLeidy Chamba
 
GeloYJ 12-CS-Resume 2016
GeloYJ 12-CS-Resume 2016GeloYJ 12-CS-Resume 2016
GeloYJ 12-CS-Resume 2016Yolanda J Gelo
 
Hydraker Technical Insight_ENG
Hydraker Technical Insight_ENGHydraker Technical Insight_ENG
Hydraker Technical Insight_ENGElias Qarmout
 

Viewers also liked (20)

Los 4 pilares de la educación
Los 4 pilares de la educaciónLos 4 pilares de la educación
Los 4 pilares de la educación
 
234
234234
234
 
Ec news latam i
Ec news latam iEc news latam i
Ec news latam i
 
L10
L10L10
L10
 
MIP 40 Colin Tate
MIP 40 Colin TateMIP 40 Colin Tate
MIP 40 Colin Tate
 
PhD project
PhD projectPhD project
PhD project
 
Памятные даты Архангельской области 2014
Памятные даты Архангельской области 2014Памятные даты Архангельской области 2014
Памятные даты Архангельской области 2014
 
Asti Aircraft Service REFERENCE LETTER
Asti Aircraft Service REFERENCE LETTERAsti Aircraft Service REFERENCE LETTER
Asti Aircraft Service REFERENCE LETTER
 
The Pearl Marrakech VH MAG
The Pearl Marrakech VH MAGThe Pearl Marrakech VH MAG
The Pearl Marrakech VH MAG
 
Chris Box letter[1].PDF
Chris Box letter[1].PDFChris Box letter[1].PDF
Chris Box letter[1].PDF
 
What have you learnt about technologies
What have you learnt about technologiesWhat have you learnt about technologies
What have you learnt about technologies
 
Carta appartenenza + scheda genitore
Carta appartenenza + scheda genitoreCarta appartenenza + scheda genitore
Carta appartenenza + scheda genitore
 
CF6-80 Hardware
CF6-80 HardwareCF6-80 Hardware
CF6-80 Hardware
 
Iberdrola lidera la clasificación de las compañías eléctricas europeas
Iberdrola lidera la clasificación de las compañías eléctricas europeasIberdrola lidera la clasificación de las compañías eléctricas europeas
Iberdrola lidera la clasificación de las compañías eléctricas europeas
 
Presentacion de un blog
Presentacion de un blogPresentacion de un blog
Presentacion de un blog
 
Real Estate
Real EstateReal Estate
Real Estate
 
L6
L6L6
L6
 
GeloYJ 12-CS-Resume 2016
GeloYJ 12-CS-Resume 2016GeloYJ 12-CS-Resume 2016
GeloYJ 12-CS-Resume 2016
 
Examen Bimestral
Examen BimestralExamen Bimestral
Examen Bimestral
 
Hydraker Technical Insight_ENG
Hydraker Technical Insight_ENGHydraker Technical Insight_ENG
Hydraker Technical Insight_ENG
 

Similar to L3

Topic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.pptTopic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.pptplagcheck
 
Datastructures using c++
Datastructures using c++Datastructures using c++
Datastructures using c++Gopi Nath
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptxselemonGamo
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
 
stack & queues .pptx
stack & queues .pptxstack & queues .pptx
stack & queues .pptxkaishsahu
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
 
computer notes - Linked list inside computer memory
computer notes - Linked list inside computer memorycomputer notes - Linked list inside computer memory
computer notes - Linked list inside computer memoryecomputernotes
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptxjack881
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
Updated Lab3.docx
Updated Lab3.docxUpdated Lab3.docx
Updated Lab3.docxAleezaAnjum
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.pptmrizwan38
 

Similar to L3 (20)

Topic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.pptTopic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.ppt
 
Datastructures using c++
Datastructures using c++Datastructures using c++
Datastructures using c++
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
 
DSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdfDSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdf
 
01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
 
01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
 
stack & queues .pptx
stack & queues .pptxstack & queues .pptx
stack & queues .pptx
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
computer notes - Linked list inside computer memory
computer notes - Linked list inside computer memorycomputer notes - Linked list inside computer memory
computer notes - Linked list inside computer memory
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
 
12888239 (2).ppt
12888239 (2).ppt12888239 (2).ppt
12888239 (2).ppt
 
03-Lists.ppt
03-Lists.ppt03-Lists.ppt
03-Lists.ppt
 
Data structures
Data structuresData structures
Data structures
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Updated Lab3.docx
Updated Lab3.docxUpdated Lab3.docx
Updated Lab3.docx
 
linkedLists.ppt
linkedLists.pptlinkedLists.ppt
linkedLists.ppt
 
COMPUTER LABORATORY-4 LAB MANUAL BE COMPUTER ENGINEERING
COMPUTER LABORATORY-4 LAB MANUAL BE COMPUTER ENGINEERINGCOMPUTER LABORATORY-4 LAB MANUAL BE COMPUTER ENGINEERING
COMPUTER LABORATORY-4 LAB MANUAL BE COMPUTER ENGINEERING
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.ppt
 

More from lksoo

More from lksoo (20)

Lo48
Lo48Lo48
Lo48
 
Lo43
Lo43Lo43
Lo43
 
Lo39
Lo39Lo39
Lo39
 
Lo37
Lo37Lo37
Lo37
 
Lo27
Lo27Lo27
Lo27
 
Lo17
Lo17Lo17
Lo17
 
Lo12
Lo12Lo12
Lo12
 
T3
T3T3
T3
 
T2
T2T2
T2
 
T1
T1T1
T1
 
T4
T4T4
T4
 
P5
P5P5
P5
 
P4
P4P4
P4
 
P3
P3P3
P3
 
P1
P1P1
P1
 
P2
P2P2
P2
 
L9
L9L9
L9
 
L8
L8L8
L8
 
L5
L5L5
L5
 
L4
L4L4
L4
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 

L3

  • 1. Binary Search Trees Christopher Simpkins chris.simpkins@gatech.edu Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 1 / 19
  • 2. Trees are everywhere. 1 1Source:http://commons.wikimedia.org/wiki/File: Winnersh_Meadows_Trees.jpg Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 2 / 19
  • 3. They’re in our web browsers. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 3 / 19
  • 4. They’re in our file systems. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 4 / 19
  • 5. They’re even in pop culture. 2 2Source: http://userserve-ak.last.fm/serve/500/44019065/Neon+Trees.png Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 5 / 19
  • 6. But they’re not in Kansas. 3 3Source: http://en.wikipedia.org/wiki/File:Wabaunsee_County_View.JPG Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 6 / 19
  • 7. Binary Tree Nodes The nodes of a binary tree have a data item, a link to a left node, and a link to a right node. private class Node<E> { E item; Node<E> left; Node<E> right; Node(E item, Node<E> left, Node<E> right) { this.item = item; this.left = left; this.right = right; } } Just as in the other linked data structures we’ve studied, binary trees are recursive. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 7 / 19
  • 8. Binary Tree Structure Every tree has a distinguished root node with no parent. All other nodes have exactly one parent. Nodes which have no children are called leaf nodes. Nodes which have children are called interior nodes. Every node has 0, 1, or 2 children. Every node can be reached by a unique path from the root node. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 8 / 19
  • 9. Binary Search Trees A binary search tree (BST) is a binary tree in which for any node, all the elements in the node’s left subtree are less than the node’s data item, and all the elements in the node’s right subtree are equal to or greater than the node’s data item. A BST is distinguished by this property, but it’s ADT is simple: add elements, find element’s in the tree, and iterate over the elements in a tree. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 9 / 19
  • 10. Maintaining The BST Property To add a new value to binary tree and maintain the BST property, we insert new nodes for data items into the left subtree of a node if the new item is less than the node’s item, or the right subtree otherwise. Every new item creates a leaf node, which can later become an interior node after additional items have been added. Here’s the structure of a BST after adding the sequence of numbers 3, 4, 1, 5, 2: Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 10 / 19
  • 11. The Path to an Item To find a path to an item in a BST: , then set the path to the empy list set the root node as the currentNode until we find the node containing the item or exhaust the BST: if currentNode contains the item, add it to the path and return it else if query item is less than the item in currentNode, add currentNode to path and set the left child as the new currentNode else add add currentNode to path and set the right child as the new currentNode if the item wasn’t found, set the path to the empty list See public List<E> path(E queryItem) in BinarySearchTree.java for the code. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 11 / 19
  • 12. Traversing a Binary Tree There are three primary ways to traverse a binary tree: Pre-order: Process node’s item. Process left subtree. Process right subtree. In-order: Process left subtree. Process node’s item. Process right subtree. Post-order: Process left subtree. Process right subtree. Process node’s item. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 12 / 19
  • 13. Simple In-Order Traversal The code for in-order traversal follows the recursive structure of the tree: public void printInOrder() { printInOrder(root); } private void printInOrder(Node<E> node) { if (node != null) { printInOrder(node.left); System.out.print(node.item + " "); printInOrder(node.right); } } The code above prints the elements in ascending order. Let’s add a printDescending() method to BinarySearchTree.java. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 13 / 19
  • 14. Recursively Building a Result: inOrderList() We can use the recursive accumulator idiom to collect the elements of the tree in an in-order traversal: public List<E> toList() { return inOrderList(root, new ArrayList<E>()); } private List<E> inOrderList(Node<E> node, List<E> accum) { if (null == node) { return accum; } else { inOrderList(node.left, accum); accum.add(node.item); inOrderList(node.right, accum); } return accum; } Again, the code follows the recursive structure of the tree. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 14 / 19
  • 15. Imperative traveral: inOrderImperative() Contrast the previous code for getting an in-order list of BST elements with an imperative version: public List<E> inOrderImperative() { Node<E> curNode = root; Stack<Node<E>> fringe = new LinkedStack<>(); List<E> accum = new ArrayList<E>(); while ((curNode != null) || !fringe.isEmpty()) { while (curNode != null) { fringe.push(curNode); curNode = curNode.left; } curNode = fringe.pop(); accum.add(curNode.item); curNode = curNode.right; } return accum; } We need extra bookkeeping variables to keep track of where we are in the tree so we can back-track. See BinarySearchTree.java for comments explaining the algorithm. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 15 / 19
  • 16. Iterators Iterators can free clients from having to implement traversal algorithms. We can even plug our data structures into Java’s for-each loop by implementing java.lang.Iterable: public interface Iterable<T> { java.util.Iterator<T> iterator(); } As a reminder, java.util.Iterator: public interface Iterator<E> { boolean hasNext(); E next(); void remove(); } Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 16 / 19
  • 17. Stateful In-Order Tree Traversal In the traversal examples we saw earlier the traversal order was effected by the method call stack. A stateful iterator is much more challenging because: The iterator must remember where it is in the tree The iterator must be able to back-track to parent nodes after processing child branches The essential implementation idea is to use a stack to store nodes for back-tracking. Traditionally (at least in AI), this “to-do list” stack is called the fringe4. Let’s look at BinarySearchTree.java again to see how we implement a stateful in-order iterator. 4This search strategy is called depth-first search. Using a queue for the fringe instead of a stack would effect a breadth-first search Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 17 / 19
  • 18. Programming Exercise 1 Add a toString method to BinarySearchTree. The string should have a left square bracket, followed by the elements in the BST in-oder separated by spaces, followed by a right square bracket. For example, [1 2 3 4 ] If the BST is empty, the string should contain empty square barckets, e.g., []. Your toString method should use a recursive helper method, similar to inOrderList. Your helper method should use a StringBuilder for its accumulator. 5 5StringBuilder works just like StringBuffer. What’s the difference? Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 18 / 19
  • 19. Programming Exercise 2 Recall the method that adds nodes to the BinarySearchTree: private Node<E> insert(E newItem, Node<E> node) { if (node == null) { return new Node<E>(newItem, null, null); } else if (newItem.compareTo(node.item) < 0) { node.left = insert(newItem, node.left); return node; } else { node.right = insert(newItem, node.right); return node; } } Notice that this implementation allows duplicate items. Modify this method so that BinarySearchTree is a set, that is, does not insert duplicate items. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming CS 1331 19 / 19