Data Structures and Algorithmsgarryowen.csis.ul.ie/~cs4115/resources/lect10.pdf · Announcements...
Transcript of Data Structures and Algorithmsgarryowen.csis.ul.ie/~cs4115/resources/lect10.pdf · Announcements...
AnnouncementsAbstract Data Types (ADTs)
Data Structures and Algorithms
P. Healy
CS1-08Computer Science Bldg.
tel: [email protected]
Spring 2018–2019
P. Healy (University of Limerick) CS4115 Spring 2018–2019 1 / 21
AnnouncementsAbstract Data Types (ADTs)
Outline
1 Announcements
2 Abstract Data Types (ADTs)Trees
Implementing TreesTree Traversals
Binary TreesBinary Search Trees
P. Healy (University of Limerick) CS4115 Spring 2018–2019 2 / 21
AnnouncementsAbstract Data Types (ADTs)
Announcements
Mid-term: bubbling up to the surface of my head
P. Healy (University of Limerick) CS4115 Spring 2018–2019 3 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Outline
1 Announcements
2 Abstract Data Types (ADTs)Trees
Implementing TreesTree Traversals
Binary TreesBinary Search Trees
P. Healy (University of Limerick) CS4115 Spring 2018–2019 4 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Introduction
A tree is defined recursively as follows:A tree is a (possibly empty) collection ofIf non-empty, the tree has one special node, r , the root, andZero or more subtrees, T1,T2, . . . ,TkSubtrees T1, . . . ,Tk are connected to r by a directed edge(from r to Ti )
The root node of a subtree is a child of r and r is theparent of each subtree root
T1 T2 T3 T4
r
P. Healy (University of Limerick) CS4115 Spring 2018–2019 5 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Introduction (contd.)
A tree of n nodes has edges since each nodeexcept r has a parent node (denoted by an edge)Nodes may have an arbitrary number of childrenNodes with are called leaf nodesLeaf nodes on 13-node tree over are E, F, K, H, I, L and MNodes with the same parent are called siblingsA path, p, from node n1 to node nk is the sequence ofnodes n1,n2, . . . ,nk such that ni is the parent of ni+1,where 1 ≤ i < kThe length of p is k − 1The length of the path from a node to itself is 0
P. Healy (University of Limerick) CS4115 Spring 2018–2019 6 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Introduction (contd.)A
B C D
E F G H I J
K L M
d=0
d=1
d=2
d=3
There is exactly one path from r to every nodeThe depth of a node, n, is the length of the path from r to nThe height of n is the length of longest path from n to a(descendant) leafNode D (above) is at depth 1 and height 2If there is a path from n1 to n2 then n1 is a (proper)ancestor of n2 and n2 is a (proper) descendant of n1 (ifn1 6= n2)
P. Healy (University of Limerick) CS4115 Spring 2018–2019 7 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
A Possible Tree Implementation
Could think of earlier tree as followsA
C D
F G H I J
L M
B
E
K
This suggests the following structstruct TreeNode // unwieldy implementation{Object el;TreeNode* firstChild;TreeNode* nextSibling;
}No need for anything more than two pointers
P. Healy (University of Limerick) CS4115 Spring 2018–2019 8 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
A Better Tree Implementation
The previous struct1 could have been useful inpre-C++ daysThe struct below requires a class but is morenatural way of thinking
struct TreeNode // more natural{
Object el; // the datalist<TreeNode> children;
}
1A struct can be thought of as a C++ object without member functionsP. Healy (University of Limerick) CS4115 Spring 2018–2019 9 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Systematically Processing a Tree
Since a tree is defined recursively, to traverse a tree wecan traverse each of its subtrees using the same algorithmThis traverses the tree depthwiseWe can “process” or “visit” the root node of each (sub)treeeither before or after we traverse its childrenProcessing the root node before (after, respectively)traversing the children is called a preorder (post-order)To “describe” or print out the names of the nodes of a treeusing preorder traversal, the code on the following slide isa rough cut at itWhat’s important is the position of the recursive call:colours match up with above
P. Healy (University of Limerick) CS4115 Spring 2018–2019 10 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Systematically Processing a Tree (contd.)
On next slide we see pseudo-C++ code for traversing atree that is represented using the second (more natural)TreeNode struct on earlier slideGiven the root of a tree we iterate over its childrentraversing each subtreeEither before that or after we print out the root’s name,indented by depth spacesObserve difference in outputs (two slides on)
Rabhadh / Attention / Achtung / Warning: Do not attempt tocompile this code
P. Healy (University of Limerick) CS4115 Spring 2018–2019 11 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Systematically Processing a Tree (contd.)
void sideways_draw_tree(const TreeNode& root,const int depth = 0)
{// use depth as indentation!!indented_print_name(root.el, depth);// cout« namefor (root.children().first(); // get first child
!root.children(); // more children?++root.children()) // get next child
sideways_draw_tree(root.children(), depth+1);// indented_print_name(root.el, depth);// cout« name}
P. Healy (University of Limerick) CS4115 Spring 2018–2019 12 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Systematically Processing a Tree (contd.)
sideways_draw_tree() traversal of previous 13-node treepre-order
|A| B| E| C| F| G| K| D| H| I| J| L| M
post-order (not just backwards pre-order!)
| E| B| F| K| G| C| H| I| L| M| J| D|A
P. Healy (University of Limerick) CS4115 Spring 2018–2019 13 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Outline
1 Announcements
2 Abstract Data Types (ADTs)Trees
Implementing TreesTree Traversals
Binary TreesBinary Search Trees
P. Healy (University of Limerick) CS4115 Spring 2018–2019 14 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
When We Limit the Number of Children...
In a binary tree a node can have at most two childrenThese are referred to as the nodes left and right childrenOn i th level of a binary tree can have at most nodesOver entire tree, number of nodes on k levels, N(k), is
N(k) =k−1∑i=0
2i = 2k − 1
So, 2k − 1 nodes can be stored using k levels
n ≤ 2k − 1
What about the other way? How many levels do we needto store n nodes?
P. Healy (University of Limerick) CS4115 Spring 2018–2019 15 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
When We Limit the Number of Children... (contd.)
From above, n ≤ 2k − 1⇒ 2k ≥ n + 1⇒ k ≥ log(n + 1)So putting 7 nodes in a binary tree cannot be done withfewer than log2 8 = 3 levels; putting 8 nodes in a treerequires minimum of log2 9 = 3.1699→ 4 levels!...must round up if necessary to next highest integer
Need at least
k ≥ dlog(n + 1)e
levels to store n nodesTherefore the to the node in a binarytree can be O(log n)This makes a binary tree potentially a useful candidate forstoring information
7 Common mistake: an n-node binary tree does not havedepth O(log n) in general
3 We want it to have depth O(log n) but we will need to dosome work to achieve it
P. Healy (University of Limerick) CS4115 Spring 2018–2019 16 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Binary Tree Examples
A
C D
F G H I J
L M
B
E
K
Tree seen earlier: n-ary treescan be faked to use just twopointers; but now siblings (e.g.,B and C) have different depth inbinary representation
null
null
null
null null
A binary tree with height, h = n
P. Healy (University of Limerick) CS4115 Spring 2018–2019 17 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
Outline
1 Announcements
2 Abstract Data Types (ADTs)Trees
Implementing TreesTree Traversals
Binary TreesBinary Search Trees
P. Healy (University of Limerick) CS4115 Spring 2018–2019 18 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
A Third Type of Tree Traversal
With a binary tree we have a type of traversal:inorderAn inorder traversal of a tree recursively traverses the leftsubtree, “visits” or “processes” the tree root and traversesthe right subtreeA binary tree is a binary search tree if an inorder traversalof the tree visits the nodes in sorted orderImportant observation: if inthe sorted order then either
the location of x is the rightmost node in y ’s left subtree, orthe location of y is the leftmost node in x ’s right subtree
P. Healy (University of Limerick) CS4115 Spring 2018–2019 19 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
A Third Type of Tree Traversal (contd.)
D
G
N
M
B
H
D
G
N
M
B
H
Binary Search Tree Binary Tree
Traversals of left and right trees above (assuming that weprocess siblings left to right):
left rightPreorder MDBGHN MDBGHNInorder BDGHMN BDHGMNPostorder BHGDNM BHGDNM
P. Healy (University of Limerick) CS4115 Spring 2018–2019 20 / 21
AnnouncementsAbstract Data Types (ADTs)
TreesBinary TreesBinary Search Trees
A bad and good BST
Abigail
Adam
Agnes
Alex
Alice
Angela
Arthur
Alex
Adam
Abigail Agnes
Angela
Alice Arthur
Tree has k = dlog(n + 1)e = 3levels, the smallest possible;this shows us that with luck(??)we can achieve a very denseand shallow tree.
P. Healy (University of Limerick) CS4115 Spring 2018–2019 21 / 21