Upload
louisa-townsend
View
213
Download
0
Tags:
Embed Size (px)
Citation preview
1
Today’s Objectives
Announcements• Hand in Homework 3 next week
Iterators Trees
• Tree terminology• Depth and height• Preorder and postorder traversals
Binary Trees• Proper binary tree• Inorder traversal• Implementing a binary tree with linked nodes• Implementing a binary tree with an array list
Week 11
2
Iterators
3
Iterator
An object used to process the elements in a data structure sequentially
An iterator always has a consistent interface for every data structure
• Iterator interface is always the same for all data structures• Client program sets up a loop that uses an iterator to process
each element
Important steps in an iterator’s implementation• Initialize the iteration• Return a copy of the next element• Implementation depends on the data structure that the iterator is
written for
Iterators (Dale, 64, 110)
4
Iterator ADT
hasNext() Test whether there are elements in the iteratorReturns: boolean
next() Return the next element and step to the next position
Returns: E
Iterators (Goodrich, 242)
5
Iterable ADT
iterator() Return an iterator of the elements in a collection
Iterators (Goodrich, 243)
All collection ADTs should implement the interable ADT, so that collection objects will be able to loop through their elements.
To guarantee this, we could make sure the data structure’s
interface extends the java.lang.Iterable interface
public interface PositionList<E> extends Iterable<E>{ public Iterator<E> iterator(); //other methods of the list ADT}
The Iterable interface requires only one method, the iterator() method, which returns an iterator
6
Using an Iterator
As long as a data structure implements the java.lang.Iterable interface, the code shown here can be used to loop through its elements, regardless of which data structure it is
Iterators (Goodrich, 243)
public static void main(String[] args){
NodePositionList<Character> myList =
new NodePositionList<Character>();
myList.addLast('a');
myList.addLast('b');
myList.addLast('c');
Iterator<Character> it = myList.iterator();
while( it.hasNext() ) {
System.out.println( it.next() );
}
}
7
For-Each Loop
The for-each loop is a shorthand way of writing a loop that iterates through all the elements stored in a data structure
However, this works only with data structures that implement the java.lang.Iterable interface
Iterators (Goodrich, 244)
public static void main(String[] args){
NodePositionList<Character> myList =
new NodePositionList<Character>();
myList.addLast('a');
myList.addLast('b');
myList.addLast('c');
for( Character c : myList ) {
System.out.println(c);
}
}
8
Trees
Chapter 7
9
Tree
Container that stores elements hierarchically.
A tree is a set of nodes storing elements in a parent-child relationship.
Trees (Goodrich, 267)
10
British Royal Family TreeTrees
Queen Victoria
King Edward VII
Albert Victor
Alice
King George V
King George VIKing Edward VIII
Queen Elizabeth II
Charles Ann Andrew Edward
William Henry Peter Zara Beatrice Eugenie
11
TerminologyTrees (Goodrich, 267)
Root
12
TerminologyTrees (Goodrich, 267)
RootParentChild
13
TerminologyTrees (Goodrich, 267)
Root
ParentChild
14
TerminologyTrees (Goodrich, 267)
Root
Tree = a set of nodes storing elements in a parent-child relationship
• A special node called the root has no parent node
• Each of the other nodes has a unique parent node
• According to our textbook, a tree may be empty
15
Are these trees?Trees
1 2
34
16
More TerminologyTrees (Goodrich, 268)
Siblings = two or more nodes that are children of the same parent
17
More TerminologyTrees (Goodrich, 268)
Siblings = two or more nodes that are children of the same parent
Internal node = node with one or more childrenExternal node = node with no childrenLeaf = external node
18
More TerminologyTrees (Goodrich, 268)
Siblings = two or more nodes that are children of the same parent
Subtree rooted at v
vv
Internal node = node with one or more childrenExternal node = node with no childrenLeaf = external node
19
Recursive Structure of TreesTrees
r
t
s
u
v
w x
20
Recursive Structure of TreesTrees
r
t
s
u
v
w x
21
Recursive Structure of TreesTrees
r
t
s
u
v
w x
22
More TerminologyTrees (Goodrich, 268)
Ancestor = parent of a node or the parent of an ancestor of a node
u
Descendent = child of a node or the child of a descendent of a node
w
3 ancestors of w
5 descendents of u
23
Varieties of Trees
Ordered Tree• The children of each node have a linear order,
e.g. first, second, third, etc.• Order is drawn from left to right• Examples: slide 8 and fig. 7.4
Binary Tree• Every node has at most two children• Child nodes are called “left child” and “right
child”
Trees (Goodrich, 271, 282)
24
Proper Binary Tree
Each node has either two children or no children To make a binary tree into a proper binary tree, we
can add empty nodes as leaves
Trees (Goodrich, 282)
25
Examples of How Trees are Used
File system – Fig. 7.3, p. 268 Ordered Tree
• Structured document – Fig. 7.4, p. 269• XML documents
Binary Trees• Decision tree – Fig. 7.10, p. 282• Expression tree – Fig. 7.11, p. 283
Trees (Goodrich, 268–269, 282–283)
26
c < b < a
Decision Tree
Represents “yes” or “no” outcomes Internal nodes are questions External nodes show what to do, based on the answers
leading to it
Trees (Goodrich, 282)
a < b ?
Yes No
b < c ? b < c ?
a < c ?a < b < c
Yes No
Yes No
a < c ?
Yes
Yes No
No
Example: What is the order of the values in the variables a, b, and c?
a < c < b c < a < b b < a < c b < c < a
27
Expression Tree
External nodes are variables or constants Internal nodes are operators, +, -, *, or /
Trees (Goodrich, 283)
*
3
-
41 2
+
What is the expression represented by this tree?
28
Tree ADT
How are the data related?• Hierarchically
Operations• Accessor operations
pos root()pos parent( pos )iter children( pos )
• Update operationsvoid replace(v,e)
Trees (Goodrich, 270)
• Query operationsbool isEmpty()int size()bool
isInternal( pos )bool
isExternal( pos )bool isRoot( pos )coll positions()iter iterator()
29
Tree Interface
public interface Tree<E> {
public int size();
public boolean isEmpty();
public Iterator<E> iterator();
public Iterable<Position<E>> positions();
public E replace(Position<E> v, E e)throws InvalidPositionException;
public Position<E> root() throws EmptyTreeException;
public Position<E> parent(Position<E> v)throws InvalidPositionException, BoundaryViolationException;
public Iterable<Position<E>> children(Position<E> v) throws InvalidPositionException;
public boolean isInternal(Position<E> v) throws InvalidPositionException;
public boolean isExternal(Position<E> v) throws InvalidPositionException;
public boolean isRoot(Position<E> v)throws InvalidPositionException;
}
Trees (Goodrich, 270)
30
Running Time AssumptionsTrees (Goodrich, 272)
O(n)iterator, positions
O(1)replace
O(1)swapElementsO(cv) (cv = no. of children of v)children
O(1)isRoot
O(1)isInternal, isExternal
O(1)parent
O(1)root
TimeMethod
31
Depth of a Node in a Tree
Depth of v = number of ancestors of v• If v is the root, v’s depth = 0• Else, v’s depth = 1 + depth of v’s parent
Trees (Goodrich, 273)
Depth
0
1 + depth( myParent ) = 1 + 0 = 1
1 + depth( myParent ) = 1 + 1 = 2
1 + depth( myParent ) = 1 + 2 = 3
32
Finding the Depth
Algorithm depth( T, v ) if T.isRoot(v) then return 0 else return 1 + depth( T, T.parent(v) )
Trees (Goodrich, 273)
33
Finding the Depth
Algorithm depth( T, v ) if T.isRoot(v) then return 0 else return 1 + depth( T, T.parent(v) )
Trees (Goodrich, 273)
public static <E> int depth(Tree<E> T, Position<E> v){ if( T.isRoot(v) ) return 0; else return 1 + depth( T, T.parent(v) );}
What is the Big-Oh if n = total number of nodes?
34
Height
Height of node v• If v is an external node, v’s height = 0• Else, v’s height = 1 + maximum height of v’s children
Trees (Goodrich, 274–275)
v
hv = 1 + max( h of myChildren ) hv = 1 + 1 = 2
h = 0 (External node)
h = 1 + max( h of myChildren )h = 1 + 0 = 1
h = 0 (External node)
35
Height
Height of node v• If v is an external node, v’s height = 0• Else, v’s height = 1 + maximum height of v’s children
Trees (Goodrich, 274–275)
v
hv = 1 + max( h of myChildren ) hv = 1 + 1 = 2
h = 0 (External node)
Height of tree T• T’s height = height of the root of T
h = 1 + max( h of myChildren )h = 1 + 0 = 1
h = 0 (External node)
36
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
T
Trees (Goodrich, 274–275)
37
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
T
Trees (Goodrich, 274–275)
38
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
return 0
return 0u
T
Trees (Goodrich, 274–275)
39
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
return 0 return 0
return 0ureturn 0v
T
Trees (Goodrich, 274–275)
40
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
return 0
return 0u
T
Trees (Goodrich, 274–275)
return 0
return 0v
return 1
41
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
return 1
return 2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
return 0 return 0
return 0ureturn 0v
T
Trees (Goodrich, 274–275)
42
Traversal
A systematic way of visiting all the nodes in a tree
When we traversed a list, it was clear which directions a traversal could go:
• Forward from the head
• Backward from the tail
A tree has more choices, so we simplify them by always starting at the root.
Trees (Goodrich, 276)
43
Preorder Traversal
One way to make sure that we visit every node
Trees (Goodrich, 276)
R
3
b
41 2
a
T
Start by visiting the root v
R
44
Preorder Traversal
One way to make sure that we visit every node
Trees (Goodrich, 276)
R
3
b
41 2
a
T
Start by visiting the root v
Then traverse each subtree v
Ra
45
Preorder Traversal
One way to make sure that we visit every node
Trees (Goodrich, 276)
R
3
b
41 2
a
T
Start by visiting the root v
Then traverse each subtree v
v
Ra1
46
Preorder Traversal
One way to make sure that we visit every node
Trees (Goodrich, 276)
R
3
b
41 2
a
T
Start by visiting the root v
Then traverse each subtree v
v v
Ra12
47
Preorder Traversal
One way to make sure that we visit every node
Trees (Goodrich, 276)
R
3
b
41 2
a
T
Start by visiting the root v
Then traverse each subtree v
v v
v
Ra12b
48
Preorder Traversal
One way to make sure that we visit every node
Trees (Goodrich, 276)
R
3
b
41 2
a
T
Start by visiting the root v
Then traverse each subtree v
v v v
v
Ra12b3
49
Preorder Traversal
One way to make sure that we visit every node
Trees (Goodrich, 276)
R
3
b
41 2
a
T
Start by visiting the root v
Then traverse each subtree v
v v v v
v
Ra12b34
50
Preorder Traversal
Algorithm preorder( T, v ) visit v for each child of v do preorder( T, child )
Trees (Goodrich, 277)
public static <E> String toStringPreorder(Tree<E> T, Position<E> v){ String s = v.element().toString(); for(Position<E> w : T.children(v)) { s += ", " + toStringPreorder(T, w); } return s;}
51
Postorder Traversal
1
Start by traversing each subtree R
3
b
41 2
a
T
v
Trees (Goodrich, 279)
52
Postorder Traversal
12
Start by traversing each subtree R
3
b
41 2
a
T
v v
Trees (Goodrich, 279)
53
Postorder Traversal
Then visit the root
12a
Start by traversing each subtree R
3
b
41 2
a
T
v
v v
Trees (Goodrich, 279)
54
Postorder Traversal
Then visit the root
12a3
Start by traversing each subtree R
3
b
41 2
a
T
v
v v v
Trees (Goodrich, 279)
55
Postorder Traversal
Then visit the root
12a34
Start by traversing each subtree R
3
b
41 2
a
T
v
v v v v
Trees (Goodrich, 279)
56
Postorder Traversal
Then visit the root
12a34b
Start by traversing each subtree R
3
b
41 2
a
T
v
v v v v
v
Trees (Goodrich, 279)
57
Postorder Traversal
Then visit the root
12a34bR
Start by traversing each subtree R
3
b
41 2
a
T
v
v
v v v v
v
Trees (Goodrich, 279)
58
Postorder Traversal
Algorithm postorder( T, v ) for each child of v do postorder( T, child ) visit v
Trees (Goodrich, 279–280)
public static <E> String toStringPostorder(Tree<E> T, Position<E> v){ String s = ""; for(Position<E> w : T.children(v)) { s += toStringPostorder(T, w) + " "; } s += v.element().toString(); return s;}
59
Tree ADT
How are the data related?• Hierarchically
Operations• Accessor operations
pos root()pos parent( pos )iter children( pos )
• Update operationsvoid replace(v,e)
Trees (Goodrich, 270)
• Query operationsbool isEmpty()int size()bool
isInternal( pos )bool
isExternal( pos )bool isRoot( pos )coll positions()iter iterator()
60
Binary Tree ADT
The Binary Tree is a specialization of the Tree ADT
Each node has either two children or no children
Child nodes are called “left child” and “right child”
Additional Operations:• Accessor operations
pos left( pos )pos right( pos )pos hasLeft( pos )pos hasRight( pos )
Trees (Goodrich, 282, 284)
61
Binary Tree Interface
public interface BinaryTree<E> extends Tree<E> {
public Position<E> left(Position<E> v)throws InvalidPositionException, BoundaryViolationException;
public Position<E> right(Position<E> v)throws InvalidPositionException, BoundaryViolationException;
public boolean hasLeft(Position<E> v)throws InvalidPositionException;
public boolean hasRight(Position<E> v) throws InvalidPositionException;
}
Trees (Goodrich, 284)
62
Linked Binary Tree
The Linked Binary Tree implements the Binary Tree ADT
It has all the Binary Tree interface methods, as well as all of the Tree interface methods
Additional operations:• Accessor operations
pos sibling( pos )
Trees (Goodrich, 289)
• Update operationspos addRoot( e )pos insertLeft( pos, e )pos insertRight( pos, e )e remove( pos )void attach(pos, T1, T2)
63
Proper Binary Tree
Each node has either two children or no children To make a binary tree into a proper binary tree, we
can add empty nodes as leaves
Trees (Goodrich, 282)
64
Properties of a Proper Binary Tree
Level = all nodes at the same depth Level d has at most 2d nodes
Trees (Goodrich, 285–286)
Level
1
0
2
Max Nodes
2
1
4
Number of external nodes: at least h+1 and at most 2h
Number of internal nodes: at least h and at most 2h – 1 Total no. nodes: at least 2h + 1 and at most 2h+1 – 1 Height: at least log(n+1) – 1 and at most (n – 1)/2 Number of external nodes = number of internal nodes + 1
Height
1
2
0 n = 7
65
Preorder and Postorder Traversals of a Binary Tree
Special cases of the traversals of the general tree
General Tree
Algorithm preorder(T,v) visit v for each child of v do preorder(T,child)
Binary Tree
Algorithm binaryPreorder(T,v) visit v if v is an internal node then binaryPreorder(T,T.left(v)) binaryPreorder(T,T.right(v))
Algorithm postorder(T,v) for each child of v do postorder(T,child) visit v
Algorithm binaryPostorder(T,v) if v is an internal node then binaryPostorder(T,T.left(v)) binaryPostorder(T,T.right(v)) visit v
Trees (Goodrich, 277)
66
Inorder Traversal of a Binary TreeTrees (Goodrich, 279)
Algorithm inorder(T,v) if v is an internal node then inorder(T,T.left(v)) visit v if v is an internal node then inorder(T,T.right(v))
*
3
+
41 2
+
T
v
1
67
Inorder Traversal of a Binary TreeTrees (Goodrich, 279)
Algorithm inorder(T,v) if v is an internal node then inorder(T,T.left(v)) visit v if v is an internal node then inorder(T,T.right(v))
*
3
+
41 2
+
T
v
v
1+
68
Inorder Traversal of a Binary TreeTrees (Goodrich, 279)
Algorithm inorder(T,v) if v is an internal node then inorder(T,T.left(v)) visit v if v is an internal node then inorder(T,T.right(v))
*
3
+
41 2
+
T
v
v v
1+2
69
Inorder Traversal of a Binary TreeTrees (Goodrich, 279)
Algorithm inorder(T,v) if v is an internal node then inorder(T,T.left(v)) visit v if v is an internal node then inorder(T,T.right(v))
*
3
+
41 2
+
T
v
v
v v
1+2*
70
Inorder Traversal of a Binary TreeTrees (Goodrich, 279)
Algorithm inorder(T,v) if v is an internal node then inorder(T,T.left(v)) visit v if v is an internal node then inorder(T,T.right(v))
*
3
+
41 2
+
T
v
v
v v v
1+2*3
71
Inorder Traversal of a Binary TreeTrees (Goodrich, 279)
Algorithm inorder(T,v) if v is an internal node then inorder(T,T.left(v)) visit v if v is an internal node then inorder(T,T.right(v))
*
3
+
41 2
+
T
v
v
v v v
v
1+2*3+
72
Inorder Traversal of a Binary TreeTrees (Goodrich, 279)
Algorithm inorder(T,v) if v is an internal node then inorder(T,T.left(v)) visit v if v is an internal node then inorder(T,T.right(v))
*
3
+
41 2
+
T
v
v
v v v v
v
1+2*3+4
73
Euler Tour Traversal
Traversal of a binary tree that starts at the root and walks around the tree
Visits each node three times (left, below, and right)
Trees (Goodrich, 303–308)
vv
v
vv
v
vv
v
vv
v
vv
v vv
v
vv
v vv
v
vv
v
2
5 1
3 2
74
Implementing a Binary Tree
75
Linked Binary Tree
Natural way to represent a tree is by using linked nodes
Trees (Goodrich, 287–295)
76
Node for a Binary Tree
leftelement
parentright
Trees (Goodrich, 287–295)
77
Node for a Binary Tree
leftelement
parentright
leftr
nullright
nulls
parentnull null
t
parentnull
root
Trees (Goodrich, 287–295)
78
Node for a Binary Tree
public class BTNode<E> implements BTPosition { private E element; public BTNode() { } public BTNode(E element, BTPosition<E> parent,
BTPosition<E> left, BTPosition<E> right) { setElement(element); setParent(parent); setLeft(left); setRight(right); } public E element() { return element; } public void setElement(E o) { element=o; } public BTPosition<E> getLeft() { return left; } public void setLeft(BTPosition<E> v) { left=v; } public BTPosition<E> getRight() { return right; } public void setRight(BTPosition<E> v) { right=v; } public BTPosition<E> getParent() { return parent; } public void setParent(BTPosition<E> v) { parent=v; }}
Trees (Goodrich, 287–295)
79
Position for a Binary Tree
public interface BTPosition<E> extends Position<E>{// inherits element()
public void setElement(E o); public BTPosition<E> getLeft(); public void setLeft(BTPosition<E> v); public BTPosition<E> getRight(); public void setRight(BTPosition<E> v); public BTPosition<E> getParent(); public void setParent(BTPosition<E> v);}
Trees (Goodrich, 287–295)
80
A Position Interface
public interface Position<E> {
/** Return the element stored at this position. */
E element();
}
A Position object, has only one operation that it can use. This operation returns the element stored inside the object.
Positions (Goodrich, 232, 234)
81
Some Operations of a Binary Tree
public class LinkedBinaryTree<E> implements BinaryTree<E> { public int size() {return size; } public boolean isEmpty() { /*...*/ } public boolean isInternal(Position<E> v) throws InvalidPositionException { checkPosition(v); return (hasLeft(v) || hasRight(v)); } public boolean isExternal(Position<E> v) throws InvalidPositionException { /*...*/ } public boolean isRoot(Position<E> v) throws InvalidPositionException { checkPosition(v); return (v == root()); } public boolean hasLeft(Position<E> v) throws InvalidPositionException { BTPosition<E> vv = checkPosition(v); return (vv.getLeft() != null); } public boolean hasRight(Position<E> v) throws InvalidPositionException { /*...*/ } public Position<E> root() throws EmptyTreeException { /*...*/ } public Position<E> left(Position<E> v) throws InvalidPositionException, BoundaryViolationException { BTPosition<E> vv = checkPosition(v); Position<E> leftPos = vv.getLeft(); if (leftPos == null) throw new BoundaryViolationException(); return leftPos;} public Position<E> right(Position<E> v) throws InvalidPositionException, BoundaryViolationException { /*...*/ }
Trees (Goodrich, 287–295)
82
Instance Variablesof a Binary Tree
public class LinkedBinaryTree<E> implements BinaryTree<E> { protected BTPosition<E> root; // reference to the root protected int size; // number of nodes
//...
Trees (Goodrich, 287–295)
83
Constructor of a Binary Tree
public class LinkedBinaryTree<E> implements BinaryTree<E> { protected BTPosition<E> root; // reference to the root protected int size; // number of nodes
public LinkedBinaryTree() { root = null; // start with an empty tree size = 0; }
//...
Trees (Goodrich, 287–295)
84
Operations of the LinkedBinaryTree
Tell us about the positionspos root()pos parent( pos )iter children( pos )bool isInternal( pos )bool isExternal( pos )bool isRoot( pos )pos left( pos )pos right( pos )pos hasLeft( pos )pos hasRight( pos )pos sibling( pos )
Tell us about the collectionint size()bool isEmpty()iter iterator()iter positions()
Update the datavoid replace( pos, e )addRoot( e )insertLeft( pos, e )insertRight( pos, e )remove( pos )attach( pos, T1, T2 )
Trees (Goodrich, 289–295)
Tree methodsBinary Tree methodsAdditional methods
85
Adding an Element to a LinkedBinaryTree Object
LinkedBinaryTree<Character> T = new LinkedBinaryTree<Character>;
Creates an empty tree.
Trees (Goodrich, 287–295)
root
86
Adding an Element to a LinkedBinaryTree Object
LinkedBinaryTree<Character> T = new LinkedBinaryTree<Character>;
Creates an empty tree.
Trees (Goodrich, 287–295)
root
AT.addRoot(new Character('A')); Adds a node as root and fills it with an element.
root
87
Adding an Element to a LinkedBinaryTree Object
LinkedBinaryTree<Character> T = new LinkedBinaryTree<Character>;
Creates an empty tree.
Trees (Goodrich, 287–295)
root
AT.addRoot(new Character('A')); Adds a node as root and fills it with an element.
root
AT.insertLeft( T.root(), new Character('B'));
Inserts the node with its element.
B
root
88
Creating a Tree with LinkedBinaryTree
A
F
C
GD E
B
Trees
89
Instantiating an EmptyLinkedBinaryTree Object
//Default constructorpublic LinkedBinaryTree(){ root = null; size = 0;}
Trees (Goodrich, 287–295)
LinkedBinaryTree<Character> T = new LinkedBinaryTree<Character>;
Creates an empty tree.
root
90
Adding a Root and Element to a LinkedBinaryTree Object
public Position<E> addRoot(E e) throws NonEmptyTreeException {
if(!isEmpty()) throw new NonEmptyTreeException(); size = 1; root = createNode(e,null,null,null); return root; }
Trees (Goodrich, 287–295)
AT.addRoot(new Character('A')); Adds a node as root and fills it with an element.
root
91
Adding Another Element to a LinkedBinaryTree Object
public Position<E> insertLeft(Position<E> v, E e) throws InvalidPositionException { BTPosition<E> vv = checkPosition(v); Position<E> leftPos = vv.getLeft(); if (leftPos != null) throw new InvalidPositionException(); BTPosition<E> ww = createNode(e, vv, null, null); vv.setLeft(ww); size++; return ww; }
Trees (Goodrich, 287–295)
AT.insertLeft( T.root(), new Character('B'));
Inserts the node with its element.
B
root
92
An Alternative Binary Tree Implementation
ArrayList Implementation
93
Binary TreeImplemented with an ArrayList
While it’s natural to think of implementing a tree with linked Nodes, a binary tree can also be implemented with an ArrayList
Advantage: better performance
Trees (Goodrich, 296–297)
94
Binary TreeImplemented as an ArrayList
Based on a way of numbering the nodes• If v is the root of T, then p(v) = 1• If v is the left child of node u, then p(v) = 2 * p(u)• If v is the right child of node u, then p(v) = 2 * p(u) + 1
Trees (Goodrich, 289–291)
D
E
F
GA C
B
1
2 3
4 5 6 7
D B F A C E G
0 1 2 3 4 5 6 7 8 9A
Example:
How would we implement root()?
95
References
Dale, N., C++ Plus Data Structures. Boston: Jones and Bartlett Publishers, 2003.
Goodrich, M. T. and R. Tamassia, Data Structures and Algorithms in Java. Hoboken, NJ: John Wiley & Sons, Inc., 2006.