CMSC 341 Data Structure Asymptotic Analysis Review

Total Page:16

File Type:pdf, Size:1020Kb

Load more

CMSC 341 Data Structure
Asymptotic Analysis Review

These questions will help test your understanding of the asymptotic analysis material discussed in class and in the text. These questions are only a study guide. Questions found here may be on your exam, although perhaps in a different format. Questions NOT found here may also be on your exam.

1. What is the purpose of asymptotic analysis?

2. Define “Big-Oh” using a formal, mathematical definition.

3. Let T1(x) = O(f(x)) and T2(x) = O(g(x)). Prove T1(x) + T2(x) = O (max(f(x), g(x))). 4. Let T(x) = O(cf(x)), where c is some positive constant. Prove T(x) = O(f(x)). 5. Let T1(x) = O(f(x)) and T2(x) = O(g(x)). Prove T1(x) * T2(x) = O(f(x) * g(x))

6. Prove 2n+1 = O(2n).

7. Prove that if T(n) is a polynomial of degree x, then T(n) = O(nx).

8. Number these functions in ascending (slowest growing to fastest growing) Big-Oh order:

  • Number
  • Big-Oh

O(n3)
O(n2 lg n)
O(1)
O(lg0.1 n) O(n1.01 O(n2.01 O(2n)

))

O(lg n) O(n)
O(n lg n) O (n lg5 n)

1
9. Determine, for the typical algorithms that you use to perform calculations by hand, the running time to:

a. Add two N-digit numbers b. Multiply two N-digit numbers

10. What is the asymptotic performance of each of the following?
Select among:

  • a. O(n)
  • b. O(n2)
  • c. O(n lg n) d. O(n3)
  • e. O(lg n)

  • f. O(1)
  • g. O(n!)

h. None of these
(a) ___________ Squaring each element of an NxN matrix (b) ___________ Finding the smallest value in a sorted array of N integers (c) ___________ Finding a value in a sorted array using binary search (d) ___________ Pushing N elements onto a stack, then popping them and printing them (e) ___________ Finding the largest 3 values in an unsorted array
11. What is the asymptotic performance of the following Java code fragment?
Justify your answer.

for (int i = 0; i < N; i++) {for (int j = 10; j >= 0; j--) {int count = 1; while (count < N) count *= 2;
}
}

2

CMSC 341 Data Structures
List Review Questions

Please refer to the textbook for List, ListNode, and ListIterator class definitions. These definitions are the same as those found in the class notes. You may assume that all member functions of these classes have been written and work properly when answering the questions below. These questions will help test your understanding of the list material discussed in class and in the text. These questions are only a study guide. Questions found here may be on your exam, although perhaps in a different format. Questions NOT found here may also be on your exam.

1. Write a new member function of the List class named ReversePrint that uses an iterator to display the elements of the List in reverse order. The data elements should be enclosed

in angle brackets (“< >”) and separated by commas. Do not construct a copy of the list

that is in reverse order, just use iterators. The prototype for ReversePrint( ) is shown below

void ReversePrint ( );

2. Write a new function named Splice( ) whose prototype is shown below. Note that

Splice( )is not a member function of the List class. This function “splices” L2 into L1 at

the specified position (posis a ListIterator over L1). If posis past end, Splice( ) does

nothing. For example, suppose L1 = {1, 2, 3, 4, 5} and L2 = {10, 20, 30} and posis constructed as list1.iterator( ) and then advanced twice (pos.next()) so it is positioned

before the “3”. Then the function call Splice( L1, L2, pos ); causes L1 to

become { 1, 2, 10, 20, 30,3, 4, 5} and L2 is unchanged. What is the asymptotic performance of Splice( )? Bear in mind that there are two lists which may be of different lengths.

public static<T> void Splice( List<T> L1, const List<T> L2, ListIterator<T> pos);

3. Complete the following table of Big-Oh, worst-case asymptotic time performance for the given operations and implementations of the List ADT. Give your answers in terms of n, the number of elements in the list.

Operation

insert (index, x ) ind( x )

  • Double Linked List
  • ArrayList

remove( x ) makeEmpty add(x )

1
4. Suppose you are provided with a set of N random numbers which are to be inserted into a sorted List (smallest to largest). What would be the worst-case asymptotic time performance for building the entire list?

5. One advantage of using a double-linked list is the availability of bi-directional list

iterators – iterators that move “forward” and move “backward”. Suppose that in order to

save memory, you (or your boss) decide to use a single linked list. Can a single linked list still support bi-directional iterators? If so, briefly describe how the iterator would move forward and backward. Be sure to include the Big-Oh performance of these operations. If bi-directional iterators are not possible with a single linked list, explain why not.

6. Describe the advantages (if any) and disadvantages (if any) of each of the List ADT implementation – singly linked list, doubly linked list, and arraylist.

7.Write the code for a new LinkedList method that removed the node AFTER the one specified by the parameter. The signature of this new method is provided below.

private AnyType removeAfter( Node<AnyType> p )

2

CMSC 341 Data Structures Stack and Queue Review

These are some review questions on stacks. The class definitions for stack and queue are provided at the end of the questions. These questions will help test your understanding of the stack and queue material discussed in class and in the text. These questions are only a study guide. Questions found here may be on your exam, although perhaps in a different format. Questions NOT found here may also be on your exam.

Stacks

1. Using only the operations of the stack, write a static function that determines if a

string is a palindrome (i.e. reads the same backward and forward; e.g. “level”). The

prototype for this function is given below.

public static bool isPalindrome(String theString);

2. What is the output of the following code?

int [] values = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19 }; Stack<Integer> s = new Stack<Integer>( );

for (int 1 = 0; i < values.length; i++) s.push( values[ i ] );

int n = 25; for (int i = 0; i < 4; i++) {n += s.pop( );
}for (int i = 0; i < 2; i++) {n -= s.pop( );
}System.out.println( n );

3. Discuss the advantages and disadvantages if the text’s array implementation and the

lecture notes layered implementation of the stack ADT. At a minimum, consider the

asymptotic time performance of the isEmpty( ), pop( )and push( )

operations.
1
4. Using only the operations of the stack given in the class, write a Java function that returns a copy of the user specified stack. The prototype for the function is given below.

public static<AnyType> Stack<AnyType> CopyStack(Stack<AnyType> otherStack)

Queues

1. Using the operations of the stack and queue, write a static function that determines if

a string is a palindrome (i.e. reads the same backward and forward; e.g. “level”). The

prototype for this function is given below.

public static bool isPalindrome(String theString );

2. Suppose that Q is an initially empty array-based queue of size 5. Show the values of the data members front and back after each statement has been executed. Indicate any errors that might occur.

Queue<Character> Q( 5 ); front = _____ back = _____

Q.enqueue ( ‘A’ ); Q.enqueue ( ‘B’ ); Q.enqueue ( ‘C’ );

char c = Q.dequeue( );

Q.enqueue ( ‘A’ );

front = _____ back = _____ front = _____ back = _____ front = _____ back = _____ front = _____ back = _____ front = _____ back = _____

3. Discuss the advantages and disadvantages of the link list and array-based implementations of a queue.

4. Describe three “real life” applications of a queue.

5. Explain how to implement a queue using two stacks.
2

Definition of the Stack Class

This is the definition of the array based stack from the text:

public class Stack<AnyType> {public Stack ( int capacity ); public boolean isEmpty( ); public boolean isFull( ); public void makeEmpty( ); public AnyType pop( ); public AnyType top( ); public void push( AnyType element ); private ArrayList< AnyType > theArray; private int topOfStack;
}

Definition of the Queue Class

This is the definition of the array based queue from the text:

public class Queue<AnyType> {public Queue( int capacity ); public boolean isEmpty( ); public boolean isFull( ); public AnyType getFront( ); public void makeEmpty( ); public AnyType dequeue( ); public void enqueue( AnyType element ); private ArrayList< AnyType > the Array private int currentSize, front, back; private void increment( int x );
}

3

CMSC 341 Data Structures
General Tree Review

These questions will help test your understanding of the general tree material discussed in class and in the text. These questions are only a study guide. Questions found here may be on your exam, although perhaps in a different format. Questions NOT found here may also be on your exam.

General Trees

1. Define tree.

2. Define k-ary tree.

3. For any tree, T, define the following a. path in T b. length of a path in T c. height of a node in T d. depth of a node in T e. height of T f. depth of T g. external node h. internal node i. leaf

4. Given the drawing of an arbitrary tree, draw the first-child, next-sibling representation of the tree.

5. Given the first-child, next-sibling representation of a tree, draw the tree. 6. Prove that there are n – 1 edges in any tree with n nodes. 7. What is the worst-case Big-Oh performance for the insert, find and remove operations in a general tree? Why is this so?

8. Write a recursive member function of the “static K-ary” tree class that counts the number

of nodes in the tree.
1

Binary Trees

1. Define binary tree, full binary tree, complete binary tree and perfect binary tree

2. Prove that a perfect binary tree of height h has 2h leaf nodes. 3. Prove that a perfect binary tree of height h has 2h+1 – 1 nodes. 4. Prove that a full binary tree with n internal nodes has n + 1 leaf nodes. 5. Prove that in any binary tree with n nodes there are n +1 “null pointers”. 6. Suppose that you have two traversals from the same binary tree. Draw the tree. pre-order: A D F G H K L P Q R W Z in-order: G F H K D L A W R Q P Z

7. Write a recursive member function of the BinaryTree class that counts the number of nodes in the tree.

8. Write a recursive member function of the BinaryTree class that counts the number of leaves in the tree.

9. Given the following binary tree containing integers, list the output from a pre-order

traversal, an in-order traversal, a post-order traversal, and a level-order traversal of the

tree.

87
114
56

93
66
42

123
39
17

29

2

CMSC 341 Data Structures Binary Search Tree Review

These questions will help test your understanding of the binary search tree material presented in class and in the text. These questions are only a study guide. Questions found here may be found on your exam, although perhaps in a different format. Questions NOT found here may also be on your exam. The necessary class definitions will be provided with your exam. Please refer to the BST and BST node class definitions in the text.

1. Define binary search tree.

2. Write the syntactically correct Java code for the private BST member function find(T x)whose function prototype is found below and cannot be changed. This private function is initially called by the public find(T x)with a reference to the root. If x is in the tree, return element in the node; otherwise return NULL.

private T find(BinaryNode<T> root, T x)

3. Describe how deletion is performed in a BST. Be sure to mention all relevant cases. 4. The number of comparisons to build a BST of n elements is O(n2) in the worst case and
O(n lg n) in the best case. Describe the best and worst case and explain why this is so.

5. Insert the following Java reserved words into an initially empty BST in the order given:

break, operator, if, typedef, else, case, while, do, return, byte, for, true, double, void.

a. Show the output from the pre-order, post-order, in-order, and level-order traversals of the BST. b. Which word is the predecessor of while? c. Which word is the successor of for? d. Draw the new tree that results from each of the following operations. Each problem is separate and begins with the tree created above. i. Insert int and float, in that order.

ii. Delete double, case, and typedef, in that order.

6. Prove that if a node in a BST has two children, its successor has at most one child. 7. Suppose the result of a post-order traversal of a BST is 1, 3, 2, 8, 10, 5, 4. Draw the original BST.

1

CMSC 341 Data Structures
Splay Tree Review

These questions will help test your understanding of the splay tree material presented in

class. Note that the splay tree presented in class is a “bottom-up” splay tree. These questions are

only a study guide. Questions found here may be found on your exam, although perhaps in a different format. Questions NOT found here may also be on your exam. The splay tree rules may be provided with your exam. Check with your instructor. Please refer to the Splay tree class definitions in the text.

1. Define splay tree.

2. Describe the splay operation. 3. Show the result of inserting the values 2, 1, 4, 5, 9, 3, 6, 7 into an empty splay tree. Show the tree at the end of each insertion. Show each rotation.

4. Explain, in English, how to insert a new element into a splay tree. Be sure to discuss the case in which a duplicate element is inserted.

5. Explain, in English, how to find an element in a splay tree. Bu sure to discuss the case in which the element is not found.

6. Explain, in English, how to remove an element from a splay tree. Be sure to discuss the case in which the element to be removed is not in the tree.

7. What does the following statement mean? In particular, what does “m” represent?

“A splay tree has O(m lg n) amoritized performance over a sequence of insert, remove

and find operations.”

8. For splay tree operations, we use amortized analysis rather than asymptotic analysis. a. What is amortized analysis? b. How is amortized analysis different than asymptotic analysis? c. Why must amortized analysis be used for splay trees?

CMSC 341 Data Structures
Red-Black Tree Review

These questions will help test your understanding of the Red-Black tree material discussed in class and in the text. These questions are only a study guide. Questions found here may be on your exam, although perhaps in a different format. Questions NOT found here may also be on your exam. The rotation diagrams for red-black trees may be provided with your exam. Check with your instructor.

1. Define Red-Black tree. List all Red-Black tree properties 2. Define the black height of a node, x. 3. What is the “Big-Oh” performance (in terms of the number of nodes in the tree) for the operations find, insert and remove for a red-black tree in the best, worst and averages cases?

4. What property of red-black trees is most significant in explaining the “Big-Oh”

performance for the operations find, insert and remove?

5. Prove that in any red-black tree with root x, there are at least n = 2bh(x) – 1 internal nodes where bh(x) is the black-height of x.

6. Prove that in any red-black tree, at least half the nodes on any path from the root to a leaf must be black.

7. Prove that in any red-black tree, no path from any node, N, to a leaf is more than twice as long as any other path from N to any other leaf.

8. Prove that if a black node has just one child, that child must be red. 9. Show the tree that results from inserting the values 2, 1, 4, 5, 9, 3, 6, 7 into an initially empty red-black tree. Show the tree after each insertion.

1
10. Given the following Red-Black Tree, show the tree that results after deleting the node with value 68 using bottom-up deletion.

87
114
56

49
166

  • 40
  • 68

Represents a BLACK node Represents a RED node

2

CMSC 341 Data Structures
K-D Tree Review

These questions will help test your understanding of k-D trees. These questions are only a study guide. Some of these questions may appear on your exam, although perhaps in a different format. Question NOT found on this study guide may also appear on your exam.

1. What is the purpose of k-D trees?

2. Explain how a 2-D tree extends a binary search tree. 3. Insert the following pairs (in the order shown) into an initially empty 2-D tree.
(53, 14), (27, 28), (30, 11), (67, 51), (70, 3)
4. Insert the following triples (in the order shown) into an initially empty 3-D tree.
(16, 8, 12), (18, 7, 15), (10, 9, 3), (13, 8, 9), (20, 10, 6), (3, 10, 7), (12, 14, 6)

1

CMSC 341 Data Structures
Priority Queue Review

These questions will help test your understanding of the priority queue material discussed in class and in the text. These questions are only a study guide. Questions found here may be on your exam, although perhaps in a different format. Questions NOT found here may also be on your exam.

1. Define the following terms a. priority b. priority queue c. min binary heap d. partial ordering e. null path length in a binary tree f. leftist binary tree g. leftist heap

2. Insertion and deletion (of the minimum element) in a min binary heap are O(lg n) on average. Explain why this is so.

3. Finding the minimum element in a min binary heap is O(1) in the worst case. Explain why this is so.

4. Although a binary heap is conceptually a binary tree, it can be implemented as an array.
Explain why this is so.

5. In a min binary heap with N elements, what is the range of indices in which the largest element will be found?

6. Describe, in English, an algorithm to find the largest element in a min binary heap. What is the asymptotic worst-case performance of your algorithm?

7. Assume that the array representing a min binary heap contains the values 2, 8, 3, 10, 16,
7, 18, 13, 15. Show the contents of the array after inserting the value 4.

8. Assume that the array representing a min binary heap contains the values 2, 8, 3, 10, 16,
7, 18, 13, 15. Show the contents of the array after deleting the minimum element.

9. Show the array representing the min binary heap constructed using the initial values 18,
2, 13, 10, 15, 3, 7, 16, 8.

10. Prove that the largest element in a min binary heap is a leaf.

1
11. Prove that a complete binary tree is a leftist tree. 12. Prove for any leftist tree with N nodes, the number of nodes, R, on the rightmost path to a non-full node is given by R < lg(N + 1)

13. Given the drawing of a binary tree, determine if the tree is a leftist tree and if it is a leftist heap. Give reasons why or why not.

14. Given the drawings of the two leftist heaps, draw the leftist heap that results from merging them.

15. Describe how to perform the findMin, insert, and deleteMin operations on a leftist heap. 16. Describe a method for constructing a leftist heap from an initial set of N values. Your algorithm must run in O(N) time.

Recommended publications
  • Search Trees

    Search Trees

    Lecture III Page 1 “Trees are the earth’s endless effort to speak to the listening heaven.” – Rabindranath Tagore, Fireflies, 1928 Alice was walking beside the White Knight in Looking Glass Land. ”You are sad.” the Knight said in an anxious tone: ”let me sing you a song to comfort you.” ”Is it very long?” Alice asked, for she had heard a good deal of poetry that day. ”It’s long.” said the Knight, ”but it’s very, very beautiful. Everybody that hears me sing it - either it brings tears to their eyes, or else -” ”Or else what?” said Alice, for the Knight had made a sudden pause. ”Or else it doesn’t, you know. The name of the song is called ’Haddocks’ Eyes.’” ”Oh, that’s the name of the song, is it?” Alice said, trying to feel interested. ”No, you don’t understand,” the Knight said, looking a little vexed. ”That’s what the name is called. The name really is ’The Aged, Aged Man.’” ”Then I ought to have said ’That’s what the song is called’?” Alice corrected herself. ”No you oughtn’t: that’s another thing. The song is called ’Ways and Means’ but that’s only what it’s called, you know!” ”Well, what is the song then?” said Alice, who was by this time completely bewildered. ”I was coming to that,” the Knight said. ”The song really is ’A-sitting On a Gate’: and the tune’s my own invention.” So saying, he stopped his horse and let the reins fall on its neck: then slowly beating time with one hand, and with a faint smile lighting up his gentle, foolish face, he began..
  • Functional Data Structures with Isabelle/HOL

    Functional Data Structures with Isabelle/HOL

    Functional Data Structures with Isabelle/HOL Tobias Nipkow Fakultät für Informatik Technische Universität München 2021-6-14 1 Part II Functional Data Structures 2 Chapter 6 Sorting 3 1 Correctness 2 Insertion Sort 3 Time 4 Merge Sort 4 1 Correctness 2 Insertion Sort 3 Time 4 Merge Sort 5 sorted :: ( 0a::linorder) list ) bool sorted [] = True sorted (x # ys) = ((8 y2set ys: x ≤ y) ^ sorted ys) 6 Correctness of sorting Specification of sort :: ( 0a::linorder) list ) 0a list: sorted (sort xs) Is that it? How about set (sort xs) = set xs Better: every x occurs as often in sort xs as in xs. More succinctly: mset (sort xs) = mset xs where mset :: 0a list ) 0a multiset 7 What are multisets? Sets with (possibly) repeated elements Some operations: f#g :: 0a multiset add mset :: 0a ) 0a multiset ) 0a multiset + :: 0a multiset ) 0a multiset ) 0a multiset mset :: 0a list ) 0a multiset set mset :: 0a multiset ) 0a set Import HOL−Library:Multiset 8 1 Correctness 2 Insertion Sort 3 Time 4 Merge Sort 9 HOL/Data_Structures/Sorting.thy Insertion Sort Correctness 10 1 Correctness 2 Insertion Sort 3 Time 4 Merge Sort 11 Principle: Count function calls For every function f :: τ 1 ) ::: ) τ n ) τ define a timing function Tf :: τ 1 ) ::: ) τ n ) nat: Translation of defining equations: E[[f p1 ::: pn = e]] = (Tf p1 ::: pn = T [[e]] + 1) Translation of expressions: T [[g e1 ::: ek]] = T [[e1]] + ::: + T [[ek]] + Tg e1 ::: ek All other operations (variable access, constants, constructors, primitive operations on bool and numbers) cost 1 time unit 12 Example: @ E[[ [] @ ys = ys ]] = (T@ [] ys = T [[ys]] + 1) = (T@ [] ys = 2) E[[ (x # xs)@ ys = x #(xs @ ys) ]] = (T@ (x # xs) ys = T [[x #(xs @ ys)]] + 1) = (T@ (x # xs) ys = T@ xs ys + 5) T [[x #(xs @ ys)]] = T [[x]] + T [[xs @ ys]] + T# x (xs @ ys) = 1 + (T [[xs]] + T [[ys]] + T@ xs ys) + 1 = 1 + (1 + 1 + T@ xs ys) + 1 13 if and case So far we model a call-by-value semantics Conditionals and case expressions are evaluated lazily.
  • Leftist Trees

    Leftist Trees

    DEMO : Purchase from www.A-PDF.com to remove the watermark5 Leftist Trees 5.1 Introduction......................................... 5-1 5.2 Height-Biased Leftist Trees ....................... 5-2 Definition • InsertionintoaMaxHBLT• Deletion of Max Element from a Max HBLT • Melding Two Max HBLTs • Initialization • Deletion of Arbitrary Element from a Max HBLT Sartaj Sahni 5.3 Weight-Biased Leftist Trees....................... 5-8 University of Florida Definition • Max WBLT Operations 5.1 Introduction A single-ended priority queue (or simply, a priority queue) is a collection of elements in which each element has a priority. There are two varieties of priority queues—max and min. The primary operations supported by a max (min) priority queue are (a) find the element with maximum (minimum) priority, (b) insert an element, and (c) delete the element whose priority is maximum (minimum). However, many authors consider additional operations such as (d) delete an arbitrary element (assuming we have a pointer to the element), (e) change the priority of an arbitrary element (again assuming we have a pointer to this element), (f) meld two max (min) priority queues (i.e., combine two max (min) priority queues into one), and (g) initialize a priority queue with a nonzero number of elements. Several data structures: e.g., heaps (Chapter 3), leftist trees [2, 5], Fibonacci heaps [7] (Chapter 7), binomial heaps [1] (Chapter 7), skew heaps [11] (Chapter 6), and pairing heaps [6] (Chapter 7) have been proposed for the representation of a priority queue. The different data structures that have been proposed for the representation of a priority queue differ in terms of the performance guarantees they provide.
  • Leftist Heap: Is a Binary Tree with the Normal Heap Ordering Property, but the Tree Is Not Balanced. in Fact It Attempts to Be Very Unbalanced!

    Leftist Heap: Is a Binary Tree with the Normal Heap Ordering Property, but the Tree Is Not Balanced. in Fact It Attempts to Be Very Unbalanced!

    Leftist heap: is a binary tree with the normal heap ordering property, but the tree is not balanced. In fact it attempts to be very unbalanced! Definition: the null path length npl(x) of node x is the length of the shortest path from x to a node without two children. The null path lengh of any node is 1 more than the minimum of the null path lengths of its children. (let npl(nil)=-1). Only the tree on the left is leftist. Null path lengths are shown in the nodes. Definition: the leftist heap property is that for every node x in the heap, the null path length of the left child is at least as large as that of the right child. This property biases the tree to get deep towards the left. It may generate very unbalanced trees, which facilitates merging! It also also means that the right path down a leftist heap is as short as any path in the heap. In fact, the right path in a leftist tree of N nodes contains at most lg(N+1) nodes. We perform all the work on this right path, which is guaranteed to be short. Merging on a leftist heap. (Notice that an insert can be considered as a merge of a one-node heap with a larger heap.) 1. (Magically and recursively) merge the heap with the larger root (6) with the right subheap (rooted at 8) of the heap with the smaller root, creating a leftist heap. Make this new heap the right child of the root (3) of h1.
  • Binary Trees, Binary Search Trees

    Binary Trees, Binary Search Trees

    Binary Trees, Binary Search Trees www.cs.ust.hk/~huamin/ COMP171/bst.ppt Trees • Linear access time of linked lists is prohibitive – Does there exist any simple data structure for which the running time of most operations (search, insert, delete) is O(log N)? Trees • A tree is a collection of nodes – The collection can be empty – (recursive definition) If not empty, a tree consists of a distinguished node r (the root), and zero or more nonempty subtrees T1, T2, ...., Tk, each of whose roots are connected by a directed edge from r Some Terminologies • Child and parent – Every node except the root has one parent – A node can have an arbitrary number of children • Leaves – Nodes with no children • Sibling – nodes with same parent Some Terminologies • Path • Length – number of edges on the path • Depth of a node – length of the unique path from the root to that node – The depth of a tree is equal to the depth of the deepest leaf • Height of a node – length of the longest path from that node to a leaf – all leaves are at height 0 – The height of a tree is equal to the height of the root • Ancestor and descendant – Proper ancestor and proper descendant Example: UNIX Directory Binary Trees • A tree in which no node can have more than two children • The depth of an “average” binary tree is considerably smaller than N, eventhough in the worst case, the depth can be as large as N – 1. Example: Expression Trees • Leaves are operands (constants or variables) • The other nodes (internal nodes) contain operators • Will not be a binary tree if some operators are not binary Tree traversal • Used to print out the data in a tree in a certain order • Pre-order traversal – Print the data at the root – Recursively print out all data in the left subtree – Recursively print out all data in the right subtree Preorder, Postorder and Inorder • Preorder traversal – node, left, right – prefix expression • ++a*bc*+*defg Preorder, Postorder and Inorder • Postorder traversal – left, right, node – postfix expression • abc*+de*f+g*+ • Inorder traversal – left, node, right.
  • Data Structures and Network Algorithms [Tarjan 1987-01-01].Pdf

    Data Structures and Network Algorithms [Tarjan 1987-01-01].Pdf

    CBMS-NSF REGIONAL CONFERENCE SERIES IN APPLIED MATHEMATICS A series of lectures on topics of current research interest in applied mathematics under the direction of the Conference Board of the Mathematical Sciences, supported by the National Science Foundation and published by SIAM. GAKRHT BiRKiion , The Numerical Solution of Elliptic Equations D. V. LINDIY, Bayesian Statistics, A Review R S. VAR<;A. Functional Analysis and Approximation Theory in Numerical Analysis R R H:\II\DI:R, Some Limit Theorems in Statistics PXIKK K Bin I.VISLI -y. Weak Convergence of Measures: Applications in Probability .1. I.. LIONS. Some Aspects of the Optimal Control of Distributed Parameter Systems R(H;I:R PI-NROSI-:. Tecltniques of Differentia/ Topology in Relativity Hi.KM \N C'ui KNOI r. Sequential Analysis and Optimal Design .1. DI'KHIN. Distribution Theory for Tests Based on the Sample Distribution Function Soi I. Ri BINO\\, Mathematical Problems in the Biological Sciences P. D. L\x. Hyperbolic Systems of Conservation Laws and the Mathematical Theory of Shock Waves I. .1. Soioi.NUiiRci. Cardinal Spline Interpolation \\.\\ SiMii.R. The Theory of Best Approximation and Functional Analysis WI-.KNI R C. RHHINBOLDT, Methods of Solving Systems of Nonlinear Equations HANS I-'. WHINBKRQKR, Variational Methods for Eigenvalue Approximation R. TYRRM.I. ROCKAI-KLI.AK, Conjugate Dtialitv and Optimization SIR JAMKS LIGHTHILL, Mathematical Biofhtiddynamics GI-.RAKD SAI.ION, Theory of Indexing C \ rnLi-:i;.N S. MORAWKTX, Notes on Time Decay and Scattering for Some Hyperbolic Problems F. Hoi'i'hNSTKAm, Mathematical Theories of Populations: Demographics, Genetics and Epidemics RK HARD ASKF;Y.
  • Problem 1: “ Buzzin' in 3-Space” (36 Pts) Problem 2:“Ding Dong Bell

    Problem 1: “ Buzzin' in 3-Space” (36 Pts) Problem 2:“Ding Dong Bell

    Name CMSC 420 Data Structures Sample Midterm Given Spring, 2000 Dr. Michelle Hugue Problem 1: “ Buzzin’ in 3-Space” (36 pts) (6) 1.1 Build a K-D tree from the set of points below using the following assumptions: • the points are inserted in alphabetical order by label • the x coordinate is the first key discriminator • if the key discriminators are equal, go left A: (0,7,1 ) B: (1,2,8) C: ( 6, 5,1) D: (4,0,6) E: (3,1,4) F: ( 4, 0,9) G: (9,9,10 ) H: (3,4,7) I: ( 1, 1,1) (6) 1.2 Explain an algorithm to identify all points within a k-d tree that are within a given distance, r, of the point (x0,y0,z0). Your algorithm should be efficient, in the sense that it should not always need to examine all the nodes. (6) 1.3 The three-dimensional analog of a point-quadtree is a point-octree. Give an expression for the minimum number of nodes in a left complete point-octree with levels numbered 0, 1,...,k. (6) 1.4 Explain the difficulties, if any, with deletion of nodes in a point octree. Hint: One way that deletions are performed is by re-inserting any nodes in the subtrees of the deleted one. Why? (6) 1.5 Describe a set of attributes of the data set, or any other reason, that would cause you to choose a k-d tree over a point-octree, and explain your reasoning. Or, if you can’t imagine ever choosing the k-d tree instead of the point-octree, explain why.
  • Priority Queues and Heaps

    Priority Queues and Heaps

    CMSC 206 Binary Heaps Priority Queues Priority Queues n Priority: some property of an object that allows it to be prioritized with respect to other objects of the same type n Min Priority Queue: homogeneous collection of Comparables with the following operations (duplicates are allowed). Smaller value means higher priority. q void insert (Comparable x) q void deleteMin( ) q Comparable findMin( ) q Construct from a set of initial values q boolean isEmpty( ) q boolean isFull( ) q void makeEmpty( ) Priority Queue Applications n Printer management: q The shorter document on the printer queue, the higher its priority. n Jobs queue within an operating system: q Users’ tasks are given priorities. System has high priority. n Simulations q The time an event “happens” is its priority. n Sorting (heap sort) q An elements “value” is its priority. Possible Implementations n Use a sorted list. Sorted by priority upon insertion. q findMin( ) --> list.front( ) q insert( ) --> list.insert( ) q deleteMin( ) --> list.erase( list.begin( ) ) n Use ordinary BST q findMin( ) --> tree.findMin( ) q insert( ) --> tree.insert( ) q deleteMin( ) --> tree.delete( tree.findMin( ) ) n Use balanced BST q guaranteed O(lg n) for Red-Black Min Binary Heap n A min binary heap is a complete binary tree with the further property that at every node neither child is smaller than the value in that node (or equivalently, both children are at least as large as that node). n This property is called a partial ordering. n As a result of this partial ordering, every path from the root to a leaf visits nodes in a non- decreasing order.
  • Merge Leftist Heaps Definition: Null Path Length

    Merge Leftist Heaps Definition: Null Path Length

    CSE 326: Data Structures New Heap Operation: Merge Given two heaps, merge them into one heap Priority Queues: – first attempt: insert each element of the smaller Leftist Heaps heap into the larger. runtime: Brian Curless Spring 2008 – second attempt: concatenate binary heaps’ arrays and run buildHeap. runtime: 1 2 Definition: Null Path Length Leftist Heaps null path length (npl) of a node x = the number of nodes between x and a null in its subtree OR Idea: npl(x) = min distance to a descendant with 0 or 1 children Focus all heap maintenance work in one • npl(null) = -1 small part of the heap • npl(leaf) = 0 • npl(single-child node) = 0 Leftist heaps: 1. Binary trees 2. Most nodes are on the left 3. All the merging work is done on the right Equivalent definition: 3 npl(x) = 1 + min{npl(left(x)), npl(right(x))} 4 Definition: Null Path Length Leftist Heap Properties Another useful definition: • Order property – parent’s priority value is ≤ to childrens’ priority npl(x) is the height of the largest perfect binary tree that is both values itself rooted at x and contained within the subtree rooted at x. –result: minimum element is at the root – (Same as binary heap) • Structure property – For every node x, npl(left(x)) ≥ npl(right(x)) –result: tree is at least as “heavy” on the left as the right (Terminology: we will say a leftist heap’s tree is a leftist 5 tree.) 6 2 Are These Leftist? 0 1 1 Observations 0 1 0 0 0 0 Are leftist trees always… 0 0 0 1 0 – complete? 0 0 1 – balanced? 2 0 00 0 1 1 0 Consider a subtree of a leftist tree… 0 1 0 0 0 0 – is it leftist? 0 0 0 0 7 Right Path in a Leftist Tree is Short (#1) Right Path in a Leftist Tree is Short (#2) Claim: The right path (path from root to rightmost Claim: If the right path has r nodes, then the tree has leaf) is as short as any in the tree.
  • CSCI-1200 Data Structures — Fall 2016 Lecture 24 – Priority Queues

    CSCI-1200 Data Structures — Fall 2016 Lecture 24 – Priority Queues

    CSCI-1200 Data Structures | Fall 2016 Lecture 24 { Priority Queues Review from Lectures 22 & 23 • Hash Tables, Hash Functions, and Collision Resolution • Performance of: Hash Tables vs. Binary Search Trees • Collision resolution: separate chaining vs open addressing • STL's unordered_set (and unordered_map) • Using a hash table to implement a set/map { Hash functions as functors/function objects { Iterators, find, insert, and erase • Using STL's for_each • Something weird & cool in C++... Function Objects, a.k.a. Functors Today's Lecture • STL Queue and STL Stack • Definition of a Binary Heap • What's a Priority Queue? • A Priority Queue as a Heap • A Heap as a Vector • Building a Heap • Heap Sort • If time allows... Merging heaps are the motivation for leftist heaps 24.1 Additional STL Container Classes: Stacks and Queues • We've studied STL vectors, lists, maps, and sets. These data structures provide a wide range of flexibility in terms of operations. One way to obtain computational efficiency is to consider a simplified set of operations or functionality. • For example, with a hash table we give up the notion of a sorted table and gain in find, insert, & erase efficiency. • 2 additional examples are: { Stacks allow access, insertion and deletion from only one end called the top ∗ There is no access to values in the middle of a stack. ∗ Stacks may be implemented efficiently in terms of vectors and lists, although vectors are preferable. ∗ All stack operations are O(1) { Queues allow insertion at one end, called the back and removal from the other end, called the front ∗ There is no access to values in the middle of a queue.
  • Heaps Or Priority Queues Npl(Node with 2 Children) = Min(Npl(Left Child), Npl(Right Child)) + 1

    Heaps Or Priority Queues Npl(Node with 2 Children) = Min(Npl(Left Child), Npl(Right Child)) + 1

    Heaps or Priority Queues Npl(node with 2 children) = min(Npl(left child), Npl(right child)) + 1 leftist heap property Ming-Hwa Wang, Ph.D. COEN 279/AMTH 377 Design and Analysis of Algorithms Npl(left child) ≥ Npl(right child) Department of Computer Engineering A leftist tree with r nodes on the right path must have at least 2r - 1 Santa Clara University nodes, i.e., a leftist tree of N nodes has a right path containing at most lg(N+1) nodes. Basic Operations perform all work on the right path Insert(H, x) insertion as a merge of a one-node heap with a larger heap DeleteMin(H) or DeleteMax(H) merge DecreaseKey(H, x, D) Recursively merge the heap with a larger root with the right sub- IncreaseKey(H, x, D) heap of the heap with the smaller root. If the result heap is not a Delete(H, x) leftist heap, swap the root's left and right children and update the h+1 BuildHeap(H), at most n/2 nodes of height h null path length. O(lgN) Merge(H1, H2) Non-recursive algorithm: First pass, create a new tree by merging the right paths of both heaps, arrange the nodes on the right paths Applications of H1 and H2 in sorted order, keeping their respective left children. operating system (scheduler) Second pass, made up the heap, and child swaps are performed at selection problem nodes that violate the leftist heap property. implementation of greedy algorithm a binary heap is a leftist heap, but not vice versa event simulation Skew Heaps Binary Heaps Skew heaps have heap order but no structural constraint.
  • CMSC 341 Data Structures Midterm II Review Red-Black Tree Review 87

    CMSC 341 Data Structures Midterm II Review Red-Black Tree Review 87

    CMSC 341 Data Structures Midterm II Review These questions will help test your understanding of the material discussed in class and in the text. These questions are only a study guide. Questions found here may be on your exam, although perhaps in a different format. Questions NOT found here may also be on your exam. Red-Black Tree Review 1. Define Red-Black tree. List all Red-Black tree properties 2. Define the black height of a node, x. 3. What is the “Big-Oh” performance (in terms of the number of nodes in the tree) for the operations find, insert and remove for a red-black tree in the best, worst and averages cases? 4. What property of red-black trees is most significant in explaining the “Big-Oh” performance for the operations find, insert and remove? 5. Prove that in any red-black tree with root x, there are at least n = 2bh(x) – 1 internal nodes where bh(x) is the black-height of x. 6. Prove that in any red-black tree, at least half the nodes on any path from the root to a leaf must be black. 7. Prove that in any red-black tree, no path from any node, N, to a leaf is more than twice as long as any other path from N to any other leaf. 8. Prove that if a black node has just one child, that child must be red. 9. Show the tree that results from inserting the values 2, 1, 4, 5, 9, 3, 6, 7 into an initially empty red-black tree.