Download Binary trees

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Linked list wikipedia , lookup

Quadtree wikipedia , lookup

Lattice model (finance) wikipedia , lookup

B-tree wikipedia , lookup

Red–black tree wikipedia , lookup

Interval tree wikipedia , lookup

Binary tree wikipedia , lookup

Binary search tree wikipedia , lookup

Transcript
Questions for Week 2
Monday
Linked Lists
1) Give three points of differences between an array and a linked list.
Array holds a fixed number of elements, linked list can grow and shrink
Array has direct access to elements, linked list need to follow from the
head
Array is allocated a fixed amount of memory, linked list uses nodes
allocated in the heap
2) Draw the stack and queue data structures with linked list
implementations for each step in the following sequence:
add(1), add(2), remove, add(3), add(4),
remove, remove, add(5).
Stack:
top 1 // (start)
top 2 > 1 //
top 1 //
top 3 > 1 //
top 4 > 3 > 1 //
top 3 > 1 //
top 1 //
top 5 > 1 // (final)
Queue:
head tail 1 //
head 1 > tail 2 //
head tail 2 //
head 2 > tail 3 //
head 2 > 3 > tail 4 //
head 3 > tail 4 //
head tail 4 //
head 4 > tail 5 //
> means next pointer, // is null
3) Let Link be an object with two member variables:
public class Link {
char item;
Link next;
}
Assume that first is a reference to a Link object containing 'a',
whose next is a link object containing 'b', whose next is null.
first
a
b
null
initial: first a > b //
Which of the following code snippets successfully reverses this structure as
follows?
null
a
b
first
final: first b > a //
Draw a picture of the result of each code snippet to explain your answer.
a)
first.next = null;
first.next.next = first;
first = first.next;
first a > b // (start)
first a // > b // (start)
null pointer exception (thrown when first.next.next called)
b)
first.next.next = first;
first = first.next;
first.next.next = null;
first a > b // (start)
b > first a > (b)
first b > a > (b)
first b > a // (final)This one
c)
Link temp = first;
first = temp.next;
first.next = temp;
temp = null;
first a > b // (start)
first temp a > b //
temp a > first b //
first b > temp a > (b)
first b > a > (b) (final)
d)
Link temp = first.next;
temp.next = first;
first.next = null;
first a > b // (start)
first temp a > b //
first temp a > b > (a)
first temp a > // b
4) A Cyclic Linked Implementation of a Queue
An (unbounded) queue can be implemented cyclically based on a
linked representation. In this case, rather than referencing "null", the
successor of the last item in the queue references the beginning of the
queue. While this is not necessary to prevent memory erosion, it does
mean that rather than having two references to the beginning and the
end of the queue, only a single reference is needed.
Write a cyclic linked implementation of a queue
called QueueLinked using this approach.
Your queue ADT must implement the QueueADT interface.
Fully document your code using javadoc comments.
5) A double-ended queue (deque) of characters differs from a standard
queue in that it allows objects to be added and deleted from both ends
of the queue. Contrast this to a standard queue, where objects can
only be added to the end of the queue and removed from the front.
Write a singly linked-list implementation of the deque ADT in Java.
Your implementation should contain the following methods:
DequeCharCyclic(s): create an empty deque of size s.
isEmpty(): return true iff the deque is empty, false otherwise.
isFull(): return true iff the deque is full, false otherwise.
pushLeft(c): add character c as the left-most character in the
deque, or throw an Overflow exception if the deque is full.
pushRight(c): add character c as the right-most character in the
deque, or throw an Overflow exception if the deque is full.
peekLeft(): return the left-most character in the deque, or throw
an Underflow exception if the deque is empty.
peekRight(): return the right-most character in the deque, or throw
an Underflow exception if the deque is empty.
popLeft(): remove and return the left-most character in the deque, or
throw an Underflow exception if the deque is empty.
popRight(): remove and return the right-most character in the
deque, or throw an Underflow exception if the deque is empty.
6) Challenge: extra questions on dequeues see
http://teaching.csse.uwa.edu.au/units/CITS2200/Tutorials/tutorial04.ht
ml
Tuesday
Trees
7) [Weiss 18.1] For the tree shown above determine:
a. which node is the root A
b. Which nodes are leaves G, H, I, L, M, K
c. What is the tree’s depth height ? 4
Sorry for the wrong term here. Question should say the height of the tree.
“The depth of a node in a tree is the length of the path from the root to the
node. Thus the depth of the root is always 0, and the depth of any node is 1
more than the depth of its parent. The height of a node in a tree is the length
of the path from the node to the deepest leaf. … Thus the height of a tree is
the height of the root.” [Weiss]
d. What are the results of traversing the tree using
i)
preorder ii) postorder iii) inorder iv) level order
preorder: A B D G H E I J L M C F K
postorder: G H D I L M J E B K F C A
inorder: G D H B I E L J M A C F K
level order: A B C D E F G H I J K L M
8) [Weiss 18.2] Create a table to show, for each node in the tree shown
above:
a. Name the parent node
b. List the children
c. List the siblings
d. Compute the height of the node
e. Compute the depth of the node
f. Compute the size of the nodes tree
Binary trees
9) State whether each of the following statements is TRUE or FALSE.
Why?
a) The height of a binary tree is O(log n)
FALSE – the tree could be unbalanced with one side longer than
log n. Worst case tree height is n.
b) The proper descendants of a node’s ancestors are also
descendants of that node.
FALSE eg above A and B are ancestors of D, B is a proper
descendent of A but is not a descendent of D
c) A binary tree always has more external nodes than internal nodes.
FALSE. Example above has 9 internal nodes and 4 external nodes
(leaves) from13 nodes in total
d) Every tree has a root node. TRUE (assuming null is not a tree)
10) [Weiss 18.9] Write efficient methods (and give their Big-Oh running
times) that take a reference to a binary tree root T and compute
a. The number of leaves in T
b. The number of nodes in T that contain one non-null child
c. The number of nodes in T that contain two non-null children
11) [Weiss 18.10] Suppose a binary tree stores integers. Write efficient
methods (and give their Big-Oh running times) that take a reference to
a binary tree root T and compute
a. The number of even data items
b. The sum of all the items in the tree
public static int treeSum(BinaryTreeNodeHomework<Integer> t)
{
if (t == null) {
return 0;
}
return (t.value + treeSum(t.left) + treeSum(t.right));
}
public static int evenNodes(BinaryTreeNodeHomework<Integer> t)
{
int e;
if (t == null) {
return 0;
}
//check if the current node is even or not
if (t.value % 2 == 0) { e = 1; } else { e = 0; }
//then count up even nodes in the rest of the tree
return (e + evenNodes(t.left) + evenNodes(t.right));
}
Wednesday
Binary search trees
12) [Weiss 19.1] Show the result of inserting 3, 1, 4, 6, 9, 2, 5, and 7 in an
initially empty binary search tree. Then show the result of deleting the
root.
2
3
1
1
4
2
4
6
6
5
9
7
5
9
7
Replace the root with the largest node from the left hand side, in this case 2.
13) [Weiss 19.2] Draw all binary search trees that can result from inserting
permutations of 1, 2, 3, and 4. How many trees are there? What are
the probabilities of each tree’s occurring if all permutations are equally
likely?
There are 24 permutations (=different orderings) of these numbers (4 x
3 x 2 x 1 = 24). Each insert order (permutation) gives rise to a
particular tree, but sometimes the same tree occurs for 2 different
permutations. For example, inserting 3124 and 3241 and 3214 all
make the same tree.
In parentheses I list the number of possible insertion sequences that
give the same tree.
1234 (1), 1243 (1), 1324 (2), 1423 (1), 1432 (1),
2143 (3), 2134 (3),
3214 (3), 3124 (3),
4321 (1), 4312 (1), 4213 (2), 4123 (1), 4132 (1). 14 trees are possible, their probabilities are calculated from the number
in brackets as eg, 1/24, 2/24 or 3/24
14) [Weiss 19.15] Implement the BinaryTree methods find, findMin, and
findMax recursively.
Note this is Binary Tree not a Binary Search Tree so you can’t rely on
the nodes being in L < P < R order and have to search the whole tree.
findMin is shown here. findMax and find are similar.
/**
* Compare two tree nodes and return the one with the min value
* @param n1 binary tree node 1
* @param n2 binary tree node 2
* @return the node with the minimum value
*/
public static BinaryTreeNodeHomework<Integer> minPair(
BinaryTreeNodeHomework<Integer> n1,
BinaryTreeNodeHomework<Integer> n2 ) {
if (n1==null && n2==null) {
throw new IllegalArgumentException("at least one node for
minPair must be non null");
}
if (n1==null) { return n2; }
if (n2==null) { return n1; }
if (n1.value <= n2.value) {
return n1;
} else {
return n2;
}
}
/**
* Find the node in a tree with the minimum value for that tree
* @param t
* @return node in t with the minimum value
*/
public static BinaryTreeNodeHomework<Integer> findMin(
BinaryTreeNodeHomework<Integer> t)
{
//base case: end of the tree
if (t==null) { return null; }
// step case, find the min of the min nodes
// of the left and right parts of the tree
return (minPair ( minPair(t, findMin(t.left)),
minPair(t, findMin(t.right)) ));
}
Thursday
Priority Queues
15) [Weiss 6.1] Show the results of the following sequence: add(4), add(8),
remove(),add(1), add(6), and remove() when the add and remove
operations correspond to the basic operations in the following:
a. Stack
b. Queue
c. Priority queue
prihead > 4 \\
prihead > 4 > 8 \\
prihead > 8 \\
prihead > 1 > 8 \\
prihead > 1 > 6 > 8 \\
prihead > 6 > 8\\
16) [Weiss 6.26] A priority queue can be implemented by using a sorted
array. Do the following:
a. Describe the algorithms for findMin, deleteMin, and insert.
NOTE this question is NOT about the binaryHeap tree array
FindMin is O(1) just returns (a[0]) (no need to delete it yet)
Delete min is O(N) since you have to move each element up one:
for (int i=0; i<a.length-1; i++) { a[i] = a[i+1]; }
Insert is O(N): search until a[i] < key < a[i+1], then move a[i+1] to
a[a.length-1] up one position, then insert key in position i+1. See the insertion
sort algorithm.
b. What is the Big-Oh running time for each of findMin, deleteMin,
and insert using these algorithms? See above
c. Write an implementation that uses these algorithms. See above
17) [Weiss 6.27] A priority queue can be implemented by storing items in an
unsorted array and inserting items in the next available location. Do the
following:
a. Describe the algorithms for findMin, deleteMin, and insert.
b. What is the Big-Oh running time for each of findMin, deleteMin,
and insert using these algorithms?
c. Write an implementation that uses these algorithms.
NOTE this question is NOT about the binaryHeap tree array
findMin is O(N) because you have to search the whole array for it.
deleteMin is O(N) assuming you search until you find key, then move all
subsequent items up one place.
insertMin is O(1), a[size] = key; size=size+1;
18) [Weiss 21.1] Describe the structure and ordering properties of the
binary heap. The structure property is that a heap is a complete binary tree — all
nodes are present as we go from top to bottom, left to right.
The ordering property is that the value stored in a node’s parent is no
larger than the value stored in a node. 19) [Weiss 21.2] In a binary heap, for an item in position i where are the
parent, left child, and right child located? The parent is in location (i / 2) (integer division, so strictly floor(i/2), the
left child is in location 2i , and the right child is in location 2i + 1. e.g. for key at index 3, parent is at pos 1, left child at 6, right child at 7.
20) [Weiss 21.3] Show the result of inserting 10, 12, 1, 14, 6, 5, 8, 15, 3,
9, 7, 4, 11, 13, and 2, one at a time, in an initially empty heap using the
add operation.
Then show the result of using the linear-time buildHeap algorithm
instead. Code from BinaryHeapPriorityQueue in code bundle
/**
* Internal method to percolate down in the heap.
* @param hole the index at which the percolate begins.
*/
private void percolateDown( int hole )
{
int child;
// save the value that will be percolated
String tmp = arr[ hole ];
//percolate down through the tree
//until the correct position is found for tmp
for( ; hole * 2 <= currentSize; hole = child )
{
//choose the smallest child: hole*2 or hole*2+1
child = hole * 2;
if( child != currentSize &&
compare( arr[ child + 1 ], arr[ child ] ) < 0 )
child++;
//if smallest child is too small, move up to parent hole
if( compare( arr[ child ], tmp ) < 0 ) {
arr[ hole ] = arr[ child ];
} else {
break;
}
}
//now we have found the right place for the value
arr[ hole ] = tmp;
}
21) Challenge: Read Weiss Section 13.2 on event-driven simulation and
implement the priority queue solution to the call bank simulation. See
exercises 13.17 and 13.18