1 trees so far…. data structures for linearly-ordered items trees … “non-linear”...
Post on 20-Dec-2015
215 views
TRANSCRIPT
1
A
B
ED
C
H
GF
I
J
LK
TREES• So far…. Data structures for linearly-ordered items
• Trees… “non-linear” arrangements of itemshierarchical organizationpart / wholeabove / belowinside / outsideancestor / descendant
…
L-17-__-19-20
[Portions © Goodrich & Tomassia]
COMP-2001 ~ Computer Science Department ~ University College Dublin ~ www.cs.ucd.ie/staff/nick ~ © Nicholas Kushmerick 2001
2
Trees• trees
• binary trees
• traversals of trees
• template method pattern
• data structures for trees
Lec 17
This week:Read Chapter 5Complete P7Start P8
3
Trees
• a tree represents a hierarchyexamples: organization structure of a corporation
table of contents of a book
Lec 17
6
Tree ADT• Trees make use of Position objects (like List & Sequence)
element()
• The Tree methods are:root() returns the Position for the rootparent(p) returns the Position of p’s parentchildren(p) returns an Iterator of the Positions
of p’s childrenisInternal(p) does p have children?isExternal(p) is p a leaf?isRoot(p) is p==root()?size() number of nodesisEmpty() always false!positions() returns an Iterator of every node
in some arbitrary order [more onspecific traversal orders in Lect 19!]
9
ADTs for Binary Trees• Just like a regular tree, but 4 additional operations
leftChild(p) return the Position of p’s left childrightChild(p) return the Position of p’s right childsibling(p) returns the other child of p’s parentexpandExternal(p) “grow” the binary tree by
converting p to a internal nodeand adding 2 new leaf nodes
(exceptions raised if the requestednode does not exist)
10
A unified hierarchy of 5 “Container” ADTs
InspectableVector InspectableList
InspectableSequenceVector List
Sequence[see G&T figures 5.11 and
6.11 for discussion]
Youare
here
Getting these interfaces “right” is acraft/art that takes years of experiences
11
Using the BinaryTree ADTBinaryTree t = new BinaryTree();
t.root().setElement(“Albert”);
t.expandExternal(tree.root());
t.root().leftChild().setElement(“Betty”);
t.root().rightChild().setElement(“Chris”);
t.expandExternal(tree.root().leftChild());
t.root().leftChild().leftChild().setElement(“David”);
t.root().leftChild().rightChild().setElement(“Elvis”);
“Albert”
“Chris”“Betty”
“Elvis”“David”
13
Implementing BinaryTree• Trees are inherently “non-linear” so it might appear that
arrays can’t be used. Not quite…… • The trick: store value at position # i,
left child at # (2i), right child at # (2i+1)
+
+ 4
3 1- 2
9 3
1 2 3 4 5 6 7 8 9 10 11
16Implementation details• class BTNode implements Position {
Object element;BTNode left, right, parent;BTNode(Object e, BTNode l, BTNode r, BTNode p) {
element=e; left=l; right=r; parent=p;}
}• class LinkedBinaryTree implements BinaryTree {
Position root;int size = 1;LinkedBinaryTree() { root = new BTNode(null,null,null.null);}boolean isInternal(Position p) { return ((BTNode)p).getLeft()!=null) && ((BTNode)p).getright()!=null);}Position leftChild(Position p) { return ((BTNode)p).getLeft();}boolean expandExternal(Position p) { ((BTNode)p).setLeft(new BTNode(null,(BTNode)p,null,null)); ((BTNode)p).setRight(new BTNode(null,(BTNode)p,null,null)); size += 2;}
...
[pages267-269
for details]
17
Tree operation #1 - depthThe depth of a node v in atree t is the number of edgesfrom the T’s root to v.
depth of Albert = 0depth of David = 2
“Albert”
“Chris”“Betty”
“Elvis”“David”
int depth(Tree t, Position p) {if (T.isRoot(p)) {
return 0;} else {
return 1 + depth(T, T.parent(p));}
}
18
DIGRESSION: Recursion• Functions can call themselves• The basic idea: express answer to some computation in
terms of same computation on “simpler” argument.• Must ensure recursion terminates eventually!• Some algorithms (eg, tree traversal!) are naturally
implemented recursively.
int factorial(int n) { if (n <= 1) { return 1; } else { return n * factorial(n-1); }}
non-recursive case toensure termination withsimplest arguments
recursive call
simpler argument
19
Writing a recursive function• Split the computation into several parts:
– some that have immediate answer• factorial(1) = 1
– and others that have answers expressible in terms of simpler results:
• factorial(n) = n * factorial(n-1)
• The “trick” is to ensure that:– the recursive call(s) must simplify the computation in some way
– must be special case(s) to handle simplest computation(s)
n! = n*(n-1)*(n-2)* …
*3*2*1
if somehow we could get
the answer to this...
… then we could get
the answer to this.
20
Recursion is very helpful for data structures that are composed of “parts” that are themselves instances of that same data structure.
The basic structure of all recursive tree operations:To do some operation on the tree, you just performthat operation on each of the tree’s children
More on recursion
a tree!
21
Tree Operation #2 - height
The height of a tree t is thenumber of edgesfrom the T’s root to v.
height of tree = 2
height of tree = height of Albert= 1 + height of Betty (ignore Chris because Betty has deeper children)
= 1 + height of David (could use Elvis instead)
= 0 = 1 = 2
“Albert”
“Chris”“Betty”
“Elvis”“David”
22
Height, continuedint height(Tree t) {
return height(T, T.root());}
int height(Tree t, Position p) {if (T.isExternal(p)) {
return 0;} else {
int h = 0;Iterator c = T.children(v);while (c.hasNext()) {
Position child = (Position) c.next();h = max(h, height(T,child));
}return 1 + h;
}}
24
Operations #3 - traversing a tree• Systematic way of “visiting” or “processing”
each node in the tree.• A very common operation:
– print out each node’s label– add 10 to each node’s label– examine each node to find label “Elvis”– count total number of nodes
…• Q: But in which order are nodes visited??• A: many “standard” orders:
– pre-order traversal– in-order traversal– post-order traversal– Euler traversal– breadth-first traversal (all nodes at depth=0, then depth=1, then depth=2)
…
Cover these now
breadth first: COMP-2006 will discuss “graphs”
25
Additions to the BinaryTree ADT
• traversal functions– Iteration inOrder();– Iteration preOrder();– Iteration postOrder();– Iteration eulerOrder();
– Returns the Positions of every nodein the specified order, as an Iterator
• Note that Tree.positions [slide 6] is alsoa traversal -- but order not specified
26
Traversing Trees - #1 - Pre-Order• preorder traversal
Algorithm preOrder(v)“visit” node vfor each child w of v do
recursively perform preOrder(w)
• EXAMPLE - readinga document frombeginning to end
Don’t reada section
until read allprior sections
27
Implementation of preOrder• Uses Java’s “Vector” to collect nodes
in the correct order•
Iteration preOrder() {Vector nodes = new Vector();preOrder(root(), nodes); // collect nodesreturn nodes.iterator(); // ‘convert’ Vector to Iterator
}void preOrder(Position p, Vector nodes) {
nodes.addElement(p); // visit this nodeif (isExternal(p)) return; // stop at leavespreOrder(leftChild(p), nodes);preOrder(rightChild(p), nodes);
}
28
Using preOrder• Example: pre-order print-out of a tree’s labels
void preOrderPrint(BinaryTree tree) {for (Iterator i = tree.preOrder(); e.hasMore(); ) {
Position p = (Position) i.next; System.out.println(p.element()); }}
Position find(BinaryTree tree, Object value) {for (Iterator i = tree.preOrder(); e.hasMore(); ) {
Position p = (Position) i.next; if (p.element.equals(value)) return p; }
return null; // not found!}
29
Traversing Trees #2 - Post-Order• postorder traversal
Algorithm postOrder(v)
for each child w of v do
recursively perform postOrder(w)
“visit” node v
• du (disk usage) command in Unix
to computevalue for parent,
must first visitall children
30
Traversing Trees - #3 - In-Order• inorder traversal of a binary tree (inapplicable to non-binary trees)
algorithm inOrder(v) recursively perform inOrder(leftChild(v)) “visit” node v recursively perform inOrder(rightChild(v))
•printing an arithmetic expressionspecialization of an inorder traversalprint “(“ before traversing the left subtreeprint “)” after traversing the right subtree
print operatorbetweenchildren
31
Traversal #4 - Euler Tour Traversal• generic traversal of a binary tree
• the preorder, inorder, and postorder traversals are special cases of the Euler tour traversal
• “walk around” the tree and visit each node three times:– on the left
– from below
– on the right
32Comparison: All 4 Traversal AlgorithmspreOrder:1. visit this node2. preOrder left child3. preOrder right childinOrder:1. inOrder left child2. visit this node3. inOrder right childpostOrder:1. postOrder left child2. postOrder right child3. visit this node
only differenceis when thisstep occurs
Euler:1. visit this node2. postOrder left child3. Visit this node4. postOrder right child5. visit this node