95
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

1 Today’s Objectives Announcements Hand in Homework 3 next week Iterators Trees Tree terminology Depth and height Preorder and postorder traversals

Embed Size (px)

Citation preview

Page 1: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 2: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

2

Iterators

Page 3: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 4: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 5: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 6: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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() );

}

}

Page 7: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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);

}

}

Page 8: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

8

Trees

Chapter 7

Page 9: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

9

Tree

Container that stores elements hierarchically.

A tree is a set of nodes storing elements in a parent-child relationship.

Trees (Goodrich, 267)

Page 10: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 11: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

11

TerminologyTrees (Goodrich, 267)

Root

Page 12: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

12

TerminologyTrees (Goodrich, 267)

RootParentChild

Page 13: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

13

TerminologyTrees (Goodrich, 267)

Root

ParentChild

Page 14: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 15: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

15

Are these trees?Trees

1 2

34

Page 16: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

16

More TerminologyTrees (Goodrich, 268)

Siblings = two or more nodes that are children of the same parent

Page 17: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 18: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 19: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

19

Recursive Structure of TreesTrees

r

t

s

u

v

w x

Page 20: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

20

Recursive Structure of TreesTrees

r

t

s

u

v

w x

Page 21: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

21

Recursive Structure of TreesTrees

r

t

s

u

v

w x

Page 22: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 23: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 24: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 25: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 26: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 27: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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?

Page 28: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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()

Page 29: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 30: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 31: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 32: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 33: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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?

Page 34: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 35: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 36: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 37: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 38: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 39: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 40: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 41: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 42: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 43: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 44: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 45: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 46: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 47: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 48: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 49: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 50: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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;}

Page 51: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

51

Postorder Traversal

1

Start by traversing each subtree R

3

b

41 2

a

T

v

Trees (Goodrich, 279)

Page 52: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

52

Postorder Traversal

12

Start by traversing each subtree R

3

b

41 2

a

T

v v

Trees (Goodrich, 279)

Page 53: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 54: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 55: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 56: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 57: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 58: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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;}

Page 59: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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()

Page 60: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 61: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 62: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 63: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 64: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 65: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 66: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 67: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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+

Page 68: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 69: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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*

Page 70: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 71: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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+

Page 72: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 73: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 74: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

74

Implementing a Binary Tree

Page 75: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

75

Linked Binary Tree

Natural way to represent a tree is by using linked nodes

Trees (Goodrich, 287–295)

Page 76: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

76

Node for a Binary Tree

leftelement

parentright

Trees (Goodrich, 287–295)

Page 77: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

77

Node for a Binary Tree

leftelement

parentright

leftr

nullright

nulls

parentnull null

t

parentnull

root

Trees (Goodrich, 287–295)

Page 78: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 79: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 80: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 81: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 82: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 83: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 84: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 85: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

85

Adding an Element to a LinkedBinaryTree Object

LinkedBinaryTree<Character> T = new LinkedBinaryTree<Character>;

Creates an empty tree.

Trees (Goodrich, 287–295)

root

Page 86: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 87: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 88: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

88

Creating a Tree with LinkedBinaryTree

A

F

C

GD E

B

Trees

Page 89: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 90: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 91: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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

Page 92: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

92

An Alternative Binary Tree Implementation

ArrayList Implementation

Page 93: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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)

Page 94: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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()?

Page 95: 1 Today’s Objectives  Announcements Hand in Homework 3 next week  Iterators  Trees Tree terminology Depth and height Preorder and postorder traversals

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.