SlideShare a Scribd company logo
1 of 29
Binary Trees
(and Big “O” notation)
CS-2303
System Programming Concepts
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and
from C: How to Program, 5th and 6th editions, by Deitel and Deitel)

CS-2303, C-Term 2010

Binary Trees

1
Definitions
• Linked List
• A data structure in which each element is
dynamically allocated and in which elements point
to each other to define a linear relationship
• Singly- or doubly-linked
• Stack, queue, circular list

• Tree
• A data structure in which each element is
dynamically allocated and in which each element
has more than one potential successor
• Defines a partial order
CS-2303, C-Term 2010

Binary Trees

2
Binary Tree
payload

• A linked list but with
two links per item
struct treeItem {
type payload;
treeItem *left;
treeItem *right;
};
payload
left

left

payload

payload
left

right

left

right

payload
left

payload
left

right

right

CS-2303, C-Term 2010

Binary Trees

3

right

right

payload
left

right
Binary Tree (continued)
• Binary tree needs a root
struct treeItem {
type payload;
treeItem *left; treeItem *right;
};
struct treeItem *root;

• Binary trees often drawn with root at top!
• Unlike ordinary trees in the forest
• More like the root systems of a tree
CS-2303, C-Term 2010

Binary Trees

4
Definitions (continued)
See Deitel & Deitel, §12.7
K & R, §6.5

• Binary Tree

• A tree in which each element has two potential
successors

• Subtree
• The set of nodes that are successors to a specific
node, either directly or indirectly

• Root of a tree
• The node of the tree that is not the successor to any
other node, all other nodes are (directly or
indirectly) successors to it
CS-2303, C-Term 2010

Binary Trees

5
Binary Tree
payload

struct treeItem {
type payload;
treeItem *left;
treeItem *right;

left

};

struct treeItem *root;

left

right

left

right

payload
left

payload
left

payload

payload

payload
left

right

right

CS-2303, C-Term 2010

Binary Trees

6

right

right

payload
left

right
Purpose of a Tree
• (Potentially) a very large data structure
• Capable of storing very many items
• In an orderly way

• Need to find items by value
• I.e., need to search through the data structure to see if it
contains an item with the value we want

• Need to add new items
• If value is not already in the tree, add a new item …
• …so that it can be easily found in future

• Why not use a linked list?
CS-2303, C-Term 2010

Binary Trees

7
Searching and Adding to a Binary Tree
• Look recursively down
sequence of branches until
either

payload
left

– Desired node is found; or
– Null branch is encountered
• Replace with ptr to new item

• Decide which branch to
follow based on payload

left

right

left

right

payload
left

payload
left

payload

payload

payload
left

right

right

CS-2303, C-Term 2010

Binary Trees

8

right

right

payload
left

right
Example — Searching a Tree
typedef struct _treeItem {
char *word;
// part of payload
int count;
// part of payload
_treeItem *left, *right;
} treeItem;
treeItem *findItem(treeItem *p, char *w) {
if (p == NULL)
return NULL; // item not found
int c = strcmp(w, p->word);
if (c == 0)
return p;
else if (c < 0)
return findItem(p->left, w);
else
return findItem(p->right, w);
}
CS-2303, C-Term 2010

Binary Trees

9
Example — Adding an Item
treeItem *addItem(treeItem *p, char *w) {
if (p == NULL){
p = malloc(sizeof(treeItem));
char *c = malloc(strlen(w)+1);
Why
p->word = strcpy(c, w);
p->count = 1;
p->left = p->right = NULL;
return p;
};
int c = strcmp(w, p->word);
if (c == 0)
p->count++;
else if (c < 0)
p->left = addItem(p->left, w);
else
p->right = addItem(p->right, w);
return p;
}
CS-2303, C-Term 2010

Binary Trees

10

do this?
Binary Tree
• Question:– how many
calls to addItem for
a tree with 106 nodes?

payload
left

right

payload

– Assume balanced
payload
– I.e., approx same number of left
right
nodes on each subtree

payload
left

right

payload
left

payload
left

left

right

CS-2303, C-Term 2010

Binary Trees

11

right

right

payload
left

right
Answer
• Approximately 20 calls to addItem
• Note:–
– 210 = 1024 ≅ 103
– Therefore 106 ≅ 220
– Therefore it takes approximately 20 two-way branches
to cover 106 items!

• How many comparisons would it take to search a
linked list of 106 items?
CS-2303, C-Term 2010

Binary Trees

12
Observation
• Problems like this occur in real life all the
time
• Need to maintain a lot of data
• Usually random

• Need to search through it quickly
• Need to add (or delete) items dynamically
• Need to sort “on the fly”
• I.e., as you are adding and/or deleting items
CS-2303, C-Term 2010

Binary Trees

13
Questions?

CS-2303, C-Term 2010

Binary Trees

14
Binary Trees (continued)
• Binary tree does not need to be “balanced”
• i.e., with approximate same # of nodes hanging from
right or left

• However, it often helps with performance
• Multiply-branched trees
• Like binary trees, but with more than two links per
node
CS-2303, C-Term 2010

Binary Trees

15
Binary Trees (continued)
• Binary tree does not need to be “balanced”
• i.e., with approximate same # of nodes hanging from
:–
right or left
tion
a

t
” no der of”
-O
Big ns “or
“
mea

• However, it helps with performance

• Time to reach a leaf node is O(log2 n), where n is
number of nodes in tree

• Multiply-branched trees
• Like binary trees, but with more than two links per
node
CS-2303, C-Term 2010

Binary Trees

16
Order of Traversing Binary Trees
• In-order
• Traverse left sub-tree (in-order)
• Visit node itself
• Traverse right sub-tree (in-order)

• Pre-order
• Visit node first
• Traverse left sub-tree
• Traverse right sub-tree

• Post-order
• Traverse left sub-tree
• Traverse right sub-tree
• Visit node last
CS-2303, C-Term 2010

Binary Trees

17
Question
• Suppose we wish to print out the strings
stored in the tree of the previous example in
alphabetical order?

• What traversal order of the tree should we
use?
CS-2303, C-Term 2010

Binary Trees

18
Another Example of Binary Tree
x = (a.real*b.imag - b.real*a.imag) /
sqrt(a.real*b.real – a.imag*b.imag)
=
x

/
sqrt

*
.
a

.
real

-

*

b

CS-2303, C-Term 2010

.
imag

b

Binary Trees

…

.
real

a
19

imag
Question
• What kind of traversal order is required for
this expression?
• In-order?
• Pre-order?
• Post-order?

CS-2303, C-Term 2010

Binary Trees

20
Binary Trees in Compilers
• Used to represent the structure of the
compiled program Deitel & Deitel, Ch 12 exercises,
Note:
• Optimizations contain a series on building a compiler
•
•
•
•
•

Common sub-expression detection
Code simplification
Loop unrolling
Parallelization
Reductions in strength – e.g., substituting additions
for multiplications, etc.
• Many others
CS-2303, C-Term 2010

Binary Trees

21
Questions?

CS-2303, C-Term 2010

Binary Trees

22
“Big O” notation
New Topic

CS-2303, C-Term 2010

Binary Trees

23
Linked Lists Again
• Linear data structure
• Easy to grow and shrink
• Easy to add and delete items

n,
to
al
on
rti r of t
o
op be lis
r
., p num the
I.e the s in
m
ite

• Time to search for an item – O(n)

CS-2303, C-Term 2010

Binary Trees

24
Binary Trees Again
• Non-linear data structure
• Easy to grow and shrink
• Easy to add and delete items

to
al f
n
tio er o
r
po umb list
p ro f n h e
.,
I.e log o s in t
m
ite

• Time to search for an item – O(log n)

CS-2303, C-Term 2010

Binary Trees

25
Definition — Big-O
“Of the order of …”
• A characterization of the number of
operations in an algorithm in terms of a
mathematical function of the number of
data items involved
• O(n) means that the number of operations to
complete the algorithm is proportional to n
• E.g., searching a list with n items requires,
on average, n/2 comparisons with payloads
CS-2303, C-Term 2010

Binary Trees

26
Big-O (continued)
•
•
•
•
•

O(n): proportional to n – i.e., linear
O(n2): proportional to n2 – i.e., quadratic
O(kn) – proportional to kn – i.e., exponential
…
O(log n) – proportional to log n – i.e.,
sublinear
• O(n log n)
• Worse than O(n), better than O(n2)

• O(1) – independent of n; i.e., constant
CS-2303, C-Term 2010

Binary Trees

27
Anecdote & Questions:–
• In the design of electronic adders, what is the
order of the carry-propagation?
• What is the order of floating point divide?
• What is the order of floating point square root?
• What program have we studied in this course that
is O(2n)? i.e., exponential?
CS-2303, C-Term 2010

Binary Trees

28
Questions on Big-O?

CS-2303, C-Term 2010

Binary Trees

29

More Related Content

What's hot

SPIRE2013-tabei20131009
SPIRE2013-tabei20131009SPIRE2013-tabei20131009
SPIRE2013-tabei20131009Yasuo Tabei
 
Frequent itemset mining using pattern growth method
Frequent itemset mining using pattern growth methodFrequent itemset mining using pattern growth method
Frequent itemset mining using pattern growth methodShani729
 
Splay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data StructuresSplay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data StructuresAmrinder Arora
 
lecture 13
lecture 13lecture 13
lecture 13sajinsc
 
Tutorial 3 (b tree min heap)
Tutorial 3 (b tree min heap)Tutorial 3 (b tree min heap)
Tutorial 3 (b tree min heap)Kira
 
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...Advanced Internet of Things firmware engineering with Thingsquare and Contiki...
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...Adam Dunkels
 
Application of hashing in better alg design tanmay
Application of hashing in better alg design tanmayApplication of hashing in better alg design tanmay
Application of hashing in better alg design tanmayTanmay 'Unsinkable'
 

What's hot (13)

SPIRE2013-tabei20131009
SPIRE2013-tabei20131009SPIRE2013-tabei20131009
SPIRE2013-tabei20131009
 
CS151 Deep copy
CS151 Deep copyCS151 Deep copy
CS151 Deep copy
 
Frequent itemset mining using pattern growth method
Frequent itemset mining using pattern growth methodFrequent itemset mining using pattern growth method
Frequent itemset mining using pattern growth method
 
Polinode guide
Polinode guidePolinode guide
Polinode guide
 
Splay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data StructuresSplay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data Structures
 
Inside database
Inside databaseInside database
Inside database
 
lecture 13
lecture 13lecture 13
lecture 13
 
Tutorial 3 (b tree min heap)
Tutorial 3 (b tree min heap)Tutorial 3 (b tree min heap)
Tutorial 3 (b tree min heap)
 
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...Advanced Internet of Things firmware engineering with Thingsquare and Contiki...
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...
 
Fp growth
Fp growthFp growth
Fp growth
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Application of hashing in better alg design tanmay
Application of hashing in better alg design tanmayApplication of hashing in better alg design tanmay
Application of hashing in better alg design tanmay
 
Assignment#12
Assignment#12Assignment#12
Assignment#12
 

Viewers also liked

20140228 fp and_performance
20140228 fp and_performance20140228 fp and_performance
20140228 fp and_performanceshinolajla
 
Big oh Representation Used in Time complexities
Big oh Representation Used in Time complexitiesBig oh Representation Used in Time complexities
Big oh Representation Used in Time complexitiesLAKSHMITHARUN PONNAM
 
What You Missed in Computer Science
What You Missed in Computer ScienceWhat You Missed in Computer Science
What You Missed in Computer ScienceTaylor Lovett
 
Scientific
ScientificScientific
Scientificapaganis
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notationsNikhil Sharma
 

Viewers also liked (8)

20140228 fp and_performance
20140228 fp and_performance20140228 fp and_performance
20140228 fp and_performance
 
Big oh Representation Used in Time complexities
Big oh Representation Used in Time complexitiesBig oh Representation Used in Time complexities
Big oh Representation Used in Time complexities
 
What You Missed in Computer Science
What You Missed in Computer ScienceWhat You Missed in Computer Science
What You Missed in Computer Science
 
Scientific
ScientificScientific
Scientific
 
Time complexity
Time complexityTime complexity
Time complexity
 
Lec1
Lec1Lec1
Lec1
 
Algorithm big o
Algorithm big oAlgorithm big o
Algorithm big o
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 

Similar to Week3 binary trees

chap11.ppt
chap11.pptchap11.ppt
chap11.pptAswiniJ6
 
II B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptxII B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptxsabithabanu83
 
lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologyKamranAli649587
 
Faster Practical Block Compression for Rank/Select Dictionaries
Faster Practical Block Compression for Rank/Select DictionariesFaster Practical Block Compression for Rank/Select Dictionaries
Faster Practical Block Compression for Rank/Select DictionariesRakuten Group, Inc.
 
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
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptxMouDhara1
 
Hub102 - Lesson4 - Data Structure
Hub102 - Lesson4 - Data StructureHub102 - Lesson4 - Data Structure
Hub102 - Lesson4 - Data StructureTiểu Hổ
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.pptRahulYadav738822
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Getachew Ganfur
 
Sequential pattern mining
Sequential pattern miningSequential pattern mining
Sequential pattern miningkiran said
 

Similar to Week3 binary trees (20)

chap11.ppt
chap11.pptchap11.ppt
chap11.ppt
 
Binary tree
Binary treeBinary tree
Binary tree
 
Editors l21 l24
Editors l21 l24Editors l21 l24
Editors l21 l24
 
linkedlist (1).ppt
linkedlist (1).pptlinkedlist (1).ppt
linkedlist (1).ppt
 
II B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptxII B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptx
 
lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminology
 
A41001011
A41001011A41001011
A41001011
 
Faster Practical Block Compression for Rank/Select Dictionaries
Faster Practical Block Compression for Rank/Select DictionariesFaster Practical Block Compression for Rank/Select Dictionaries
Faster Practical Block Compression for Rank/Select Dictionaries
 
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
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptx
 
Hub102 - Lesson4 - Data Structure
Hub102 - Lesson4 - Data StructureHub102 - Lesson4 - Data Structure
Hub102 - Lesson4 - Data Structure
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.ppt
 
Data Structures 5
Data Structures 5Data Structures 5
Data Structures 5
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
 
lecture4.pdf
lecture4.pdflecture4.pdf
lecture4.pdf
 
Realtime Analytics
Realtime AnalyticsRealtime Analytics
Realtime Analytics
 
Join Operation.pptx
Join Operation.pptxJoin Operation.pptx
Join Operation.pptx
 
Sequential pattern mining
Sequential pattern miningSequential pattern mining
Sequential pattern mining
 
L 15 ct1120
L 15 ct1120L 15 ct1120
L 15 ct1120
 
210 trees
210 trees210 trees
210 trees
 

More from Susant Sahani

How to debug systemd problems fedora project
How to debug systemd problems   fedora projectHow to debug systemd problems   fedora project
How to debug systemd problems fedora projectSusant Sahani
 
Systemd vs-sys vinit-cheatsheet.jpg
Systemd vs-sys vinit-cheatsheet.jpgSystemd vs-sys vinit-cheatsheet.jpg
Systemd vs-sys vinit-cheatsheet.jpgSusant Sahani
 
Systemd for administrators
Systemd for administratorsSystemd for administrators
Systemd for administratorsSusant Sahani
 
Systemd mlug-20140614
Systemd mlug-20140614Systemd mlug-20140614
Systemd mlug-20140614Susant Sahani
 
Summit demystifying systemd1
Summit demystifying systemd1Summit demystifying systemd1
Summit demystifying systemd1Susant Sahani
 
Systemd evolution revolution_regression
Systemd evolution revolution_regressionSystemd evolution revolution_regression
Systemd evolution revolution_regressionSusant Sahani
 
Systemd for administrators
Systemd for administratorsSystemd for administrators
Systemd for administratorsSusant Sahani
 
Interface between kernel and user space
Interface between kernel and user spaceInterface between kernel and user space
Interface between kernel and user spaceSusant Sahani
 
Van jaconson netchannels
Van jaconson netchannelsVan jaconson netchannels
Van jaconson netchannelsSusant Sahani
 
Synchronization linux
Synchronization linuxSynchronization linux
Synchronization linuxSusant Sahani
 

More from Susant Sahani (20)

systemd
systemdsystemd
systemd
 
systemd
systemdsystemd
systemd
 
How to debug systemd problems fedora project
How to debug systemd problems   fedora projectHow to debug systemd problems   fedora project
How to debug systemd problems fedora project
 
Systemd vs-sys vinit-cheatsheet.jpg
Systemd vs-sys vinit-cheatsheet.jpgSystemd vs-sys vinit-cheatsheet.jpg
Systemd vs-sys vinit-cheatsheet.jpg
 
Systemd cheatsheet
Systemd cheatsheetSystemd cheatsheet
Systemd cheatsheet
 
Systemd
SystemdSystemd
Systemd
 
Systemd for administrators
Systemd for administratorsSystemd for administrators
Systemd for administrators
 
Pdf c1t tlawaxb
Pdf c1t tlawaxbPdf c1t tlawaxb
Pdf c1t tlawaxb
 
Systemd mlug-20140614
Systemd mlug-20140614Systemd mlug-20140614
Systemd mlug-20140614
 
Summit demystifying systemd1
Summit demystifying systemd1Summit demystifying systemd1
Summit demystifying systemd1
 
Systemd evolution revolution_regression
Systemd evolution revolution_regressionSystemd evolution revolution_regression
Systemd evolution revolution_regression
 
Systemd for administrators
Systemd for administratorsSystemd for administrators
Systemd for administrators
 
Systemd poettering
Systemd poetteringSystemd poettering
Systemd poettering
 
Interface between kernel and user space
Interface between kernel and user spaceInterface between kernel and user space
Interface between kernel and user space
 
Van jaconson netchannels
Van jaconson netchannelsVan jaconson netchannels
Van jaconson netchannels
 
Trees
TreesTrees
Trees
 
Synchronization linux
Synchronization linuxSynchronization linux
Synchronization linux
 
Demo preorder-stack
Demo preorder-stackDemo preorder-stack
Demo preorder-stack
 
Bacnet white paper
Bacnet white paperBacnet white paper
Bacnet white paper
 
Api presentation
Api presentationApi presentation
Api presentation
 

Recently uploaded

Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy Verified Accounts
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCRashishs7044
 
International Business Environments and Operations 16th Global Edition test b...
International Business Environments and Operations 16th Global Edition test b...International Business Environments and Operations 16th Global Edition test b...
International Business Environments and Operations 16th Global Edition test b...ssuserf63bd7
 
Kenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith PereraKenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith Pereraictsugar
 
Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Anamaria Contreras
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...ictsugar
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfRbc Rbcua
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCRashishs7044
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 
Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africaictsugar
 
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deckPitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deckHajeJanKamps
 
Future Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionFuture Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionMintel Group
 
Investment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy CheruiyotInvestment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy Cheruiyotictsugar
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis UsageNeil Kimberley
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessSeta Wicaksana
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncrdollysharma2066
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfJos Voskuil
 

Recently uploaded (20)

Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail Accounts
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
 
International Business Environments and Operations 16th Global Edition test b...
International Business Environments and Operations 16th Global Edition test b...International Business Environments and Operations 16th Global Edition test b...
International Business Environments and Operations 16th Global Edition test b...
 
Kenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith PereraKenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith Perera
 
Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdf
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 
Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africa
 
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deckPitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
 
Future Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionFuture Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted Version
 
Corporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information TechnologyCorporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information Technology
 
Investment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy CheruiyotInvestment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy Cheruiyot
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful Business
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdf
 
Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)
 

Week3 binary trees

  • 1. Binary Trees (and Big “O” notation) CS-2303 System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and from C: How to Program, 5th and 6th editions, by Deitel and Deitel) CS-2303, C-Term 2010 Binary Trees 1
  • 2. Definitions • Linked List • A data structure in which each element is dynamically allocated and in which elements point to each other to define a linear relationship • Singly- or doubly-linked • Stack, queue, circular list • Tree • A data structure in which each element is dynamically allocated and in which each element has more than one potential successor • Defines a partial order CS-2303, C-Term 2010 Binary Trees 2
  • 3. Binary Tree payload • A linked list but with two links per item struct treeItem { type payload; treeItem *left; treeItem *right; }; payload left left payload payload left right left right payload left payload left right right CS-2303, C-Term 2010 Binary Trees 3 right right payload left right
  • 4. Binary Tree (continued) • Binary tree needs a root struct treeItem { type payload; treeItem *left; treeItem *right; }; struct treeItem *root; • Binary trees often drawn with root at top! • Unlike ordinary trees in the forest • More like the root systems of a tree CS-2303, C-Term 2010 Binary Trees 4
  • 5. Definitions (continued) See Deitel & Deitel, §12.7 K & R, §6.5 • Binary Tree • A tree in which each element has two potential successors • Subtree • The set of nodes that are successors to a specific node, either directly or indirectly • Root of a tree • The node of the tree that is not the successor to any other node, all other nodes are (directly or indirectly) successors to it CS-2303, C-Term 2010 Binary Trees 5
  • 6. Binary Tree payload struct treeItem { type payload; treeItem *left; treeItem *right; left }; struct treeItem *root; left right left right payload left payload left payload payload payload left right right CS-2303, C-Term 2010 Binary Trees 6 right right payload left right
  • 7. Purpose of a Tree • (Potentially) a very large data structure • Capable of storing very many items • In an orderly way • Need to find items by value • I.e., need to search through the data structure to see if it contains an item with the value we want • Need to add new items • If value is not already in the tree, add a new item … • …so that it can be easily found in future • Why not use a linked list? CS-2303, C-Term 2010 Binary Trees 7
  • 8. Searching and Adding to a Binary Tree • Look recursively down sequence of branches until either payload left – Desired node is found; or – Null branch is encountered • Replace with ptr to new item • Decide which branch to follow based on payload left right left right payload left payload left payload payload payload left right right CS-2303, C-Term 2010 Binary Trees 8 right right payload left right
  • 9. Example — Searching a Tree typedef struct _treeItem { char *word; // part of payload int count; // part of payload _treeItem *left, *right; } treeItem; treeItem *findItem(treeItem *p, char *w) { if (p == NULL) return NULL; // item not found int c = strcmp(w, p->word); if (c == 0) return p; else if (c < 0) return findItem(p->left, w); else return findItem(p->right, w); } CS-2303, C-Term 2010 Binary Trees 9
  • 10. Example — Adding an Item treeItem *addItem(treeItem *p, char *w) { if (p == NULL){ p = malloc(sizeof(treeItem)); char *c = malloc(strlen(w)+1); Why p->word = strcpy(c, w); p->count = 1; p->left = p->right = NULL; return p; }; int c = strcmp(w, p->word); if (c == 0) p->count++; else if (c < 0) p->left = addItem(p->left, w); else p->right = addItem(p->right, w); return p; } CS-2303, C-Term 2010 Binary Trees 10 do this?
  • 11. Binary Tree • Question:– how many calls to addItem for a tree with 106 nodes? payload left right payload – Assume balanced payload – I.e., approx same number of left right nodes on each subtree payload left right payload left payload left left right CS-2303, C-Term 2010 Binary Trees 11 right right payload left right
  • 12. Answer • Approximately 20 calls to addItem • Note:– – 210 = 1024 ≅ 103 – Therefore 106 ≅ 220 – Therefore it takes approximately 20 two-way branches to cover 106 items! • How many comparisons would it take to search a linked list of 106 items? CS-2303, C-Term 2010 Binary Trees 12
  • 13. Observation • Problems like this occur in real life all the time • Need to maintain a lot of data • Usually random • Need to search through it quickly • Need to add (or delete) items dynamically • Need to sort “on the fly” • I.e., as you are adding and/or deleting items CS-2303, C-Term 2010 Binary Trees 13
  • 15. Binary Trees (continued) • Binary tree does not need to be “balanced” • i.e., with approximate same # of nodes hanging from right or left • However, it often helps with performance • Multiply-branched trees • Like binary trees, but with more than two links per node CS-2303, C-Term 2010 Binary Trees 15
  • 16. Binary Trees (continued) • Binary tree does not need to be “balanced” • i.e., with approximate same # of nodes hanging from :– right or left tion a t ” no der of” -O Big ns “or “ mea • However, it helps with performance • Time to reach a leaf node is O(log2 n), where n is number of nodes in tree • Multiply-branched trees • Like binary trees, but with more than two links per node CS-2303, C-Term 2010 Binary Trees 16
  • 17. Order of Traversing Binary Trees • In-order • Traverse left sub-tree (in-order) • Visit node itself • Traverse right sub-tree (in-order) • Pre-order • Visit node first • Traverse left sub-tree • Traverse right sub-tree • Post-order • Traverse left sub-tree • Traverse right sub-tree • Visit node last CS-2303, C-Term 2010 Binary Trees 17
  • 18. Question • Suppose we wish to print out the strings stored in the tree of the previous example in alphabetical order? • What traversal order of the tree should we use? CS-2303, C-Term 2010 Binary Trees 18
  • 19. Another Example of Binary Tree x = (a.real*b.imag - b.real*a.imag) / sqrt(a.real*b.real – a.imag*b.imag) = x / sqrt * . a . real - * b CS-2303, C-Term 2010 . imag b Binary Trees … . real a 19 imag
  • 20. Question • What kind of traversal order is required for this expression? • In-order? • Pre-order? • Post-order? CS-2303, C-Term 2010 Binary Trees 20
  • 21. Binary Trees in Compilers • Used to represent the structure of the compiled program Deitel & Deitel, Ch 12 exercises, Note: • Optimizations contain a series on building a compiler • • • • • Common sub-expression detection Code simplification Loop unrolling Parallelization Reductions in strength – e.g., substituting additions for multiplications, etc. • Many others CS-2303, C-Term 2010 Binary Trees 21
  • 23. “Big O” notation New Topic CS-2303, C-Term 2010 Binary Trees 23
  • 24. Linked Lists Again • Linear data structure • Easy to grow and shrink • Easy to add and delete items n, to al on rti r of t o op be lis r ., p num the I.e the s in m ite • Time to search for an item – O(n) CS-2303, C-Term 2010 Binary Trees 24
  • 25. Binary Trees Again • Non-linear data structure • Easy to grow and shrink • Easy to add and delete items to al f n tio er o r po umb list p ro f n h e ., I.e log o s in t m ite • Time to search for an item – O(log n) CS-2303, C-Term 2010 Binary Trees 25
  • 26. Definition — Big-O “Of the order of …” • A characterization of the number of operations in an algorithm in terms of a mathematical function of the number of data items involved • O(n) means that the number of operations to complete the algorithm is proportional to n • E.g., searching a list with n items requires, on average, n/2 comparisons with payloads CS-2303, C-Term 2010 Binary Trees 26
  • 27. Big-O (continued) • • • • • O(n): proportional to n – i.e., linear O(n2): proportional to n2 – i.e., quadratic O(kn) – proportional to kn – i.e., exponential … O(log n) – proportional to log n – i.e., sublinear • O(n log n) • Worse than O(n), better than O(n2) • O(1) – independent of n; i.e., constant CS-2303, C-Term 2010 Binary Trees 27
  • 28. Anecdote & Questions:– • In the design of electronic adders, what is the order of the carry-propagation? • What is the order of floating point divide? • What is the order of floating point square root? • What program have we studied in this course that is O(2n)? i.e., exponential? CS-2303, C-Term 2010 Binary Trees 28
  • 29. Questions on Big-O? CS-2303, C-Term 2010 Binary Trees 29

Editor's Notes

  1. &lt;number&gt;