trees cmput 115 - lecture 22 department of computing science university of alberta ©duane szafron...

62
Trees Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package Revised 3/7/00

Post on 22-Dec-2015

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

TreesTrees

Cmput 115 - Lecture 22

Department of Computing Science

University of Alberta©Duane Szafron 2000

Some code in this lecture is based on code from the book:Java Structures by Duane A. Bailey or the companion structure package

Revised 3/7/00

Page 2: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

2

About This LectureAbout This Lecture

In this lecture we study a non-linear container called a Tree and a special kind of Tree called a Binary Tree.

Page 3: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

3

OutlineOutline

Tree Terminology Binary Tree Interface Example - Expression Trees Binary Tree Implementation Tree Traversals Tree Property-based methods

Page 4: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

4

Trees - Trees - Empty and SingletonEmpty and Singleton

We will define a tree recursively.

An empty container is a tree called an empty tree or a trivial tree.

A container that contains a single element is a singleton tree and the element is called the root node or root of the tree

43 root node

Page 5: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

5

Trees - Trees - Combining singletonsCombining singletons

A singleton tree, S, and one or more other non-empty trees can be combined into a new tree by creating a binary relation between S and each of the other trees.– Each binary relation is called an edge.– The root node from the singleton tree is called

the root node of the new tree. The root nodes of the other trees are called non-root nodes in the new tree.

SS

43

1721 6743

17

21 67

root node

non-root nodes

edge

Page 6: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

6

Trees - Trees - Combining generalCombining general

This recursive definition can be applied more times to yield more complex trees.

We always draw the root node at the top.

S

43

1721 67

25

13 90

10

55

root nodeS

10

55 43

1721 67

25

13 90

Page 7: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

7

Trees - Trees - forests,disjoint trees and subtreesforests,disjoint trees and subtrees

A forest is a set of trees. Two trees are disjoint if they share no nodes and no edges. A tree T1 is a subtree of a tree T2 if all of the nodes and edges of T1 are also in

T2.

43

1721 67

25

13 90

1055

forest

disjoint trees

subtrees

10

55 43

1721 67

25

13 90

Page 8: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

8

Trees - Trees - node relationshipsnode relationships

The root node of a tree is an ancestor of all nodes in that tree.

The parent of a node is an ancestor that is connected to it by an edge.

If node N1 is a parent of node N2, then N2 is a child of N1.

If node N1 is an ancestor of node N2, then N2 is a descendant of N1.

The root node has no parent. A node with no children is called a leaf node. A node with children is called an interior node. Two nodes are siblings if they have the same parent.

Page 9: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

9

Trees - Trees - node relationships examplenode relationships example

The ancestors of node 21 are nodes: 43 and 10. The parent of node 21 is node 43. The children of node 43 are nodes: 21, 17 and 67. The descendants of node 43 are nodes: 21, 17, 67,

15, 11, 88 and 99.

10

55 43

1721 67

25

13 90

15

11 88

The leaf nodes are: 55, 21, 11, 88, 99, 13 and 90.

The interior nodes are: 10, 43, 25, 17, 67 and 15.

The siblings of node 21 are nodes: 17 and 67.

99

Page 10: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

10

Measuring TreesMeasuring Trees A path is the unique shortest sequence of edges

from a node to an ancestor. The length of a path is the number of edges in it. The height of a node is the length of the longest

path from a leaf to the node. The height of a tree is the height of its root. The depth (level) of a node is the length of the

path from the root to the node. The degree of a node is the number of children it

has. The degree (arity) of a tree is the maximum degree

of its nodes.

Page 11: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

11

Measuring Trees - ExampleMeasuring Trees - Example The path from node 88 to 43 is highlighted in red. The length of the path from node 88 to node 43 is 3. The height of node 43 is 3. The height of the tree is the height of node 10: 4.

10

55 43

1721 67

25

13 90

15

11 88

The depth (level) of node 67 is the length of the path from node 10 to node 67 which is 2.

The degree of node 43 is 3 and the degree of node 25 is 2 and the degree of node 11 is 0.

The degree of the tree is 3.

99

Page 12: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

12

Notation mini-testNotation mini-test

10

55 43

1721 67

25

19 90

15

11 88

9912 78 13 82

Depth of the tree?4

Number of ancestors fornode 15?3

Height of node 13? 0 Node 25? 3

Node 43 has how many descendents?8M-arity of the tree?4

Degree of node 43?3 90?1 55?0

Length of longest path on the tree?4

Is the the tree full? NO

Page 13: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

13

Binary TreesBinary Trees A binary tree is a tree with arity 2. A binary tree is oriented if every node with 2 children differentiates between the children

by calling them the left child and right child and every node with one child designates it either as a left child or right child.

A node in a binary tree is full if it has arity 2. A full binary tree of height h has leaves only on level h and each of its interior nodes is

full. A complete binary tree of height h is a full binary tree of height h with 0 or more of the

rightmost leaves of level h removed.

Page 14: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

14

Binary Tree ExamplesBinary Tree Examples Node 55 is full in all trees since it has arity 2 in all

of them. Node 20 is full in the left tree, but not full in the

middle tree where it has arity 0 and not full in the right tree where it has arity 1.

55

10

25 90

20

35 80

full binary tree

55

10

25 90

20

non-full butcomplete binary tree

55

10

25

20

35

non-completebinary tree

Page 15: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

15

Interface for Binary TreesInterface for Binary Trees The structure package does not define a Java

Interface for BinaryTree.

Instead it defines a BinaryTree class, just as it defines a Vector class.

The BinaryTree class defines the three methods that are in the Store Interface (size, isEmpty, clear), but it is not defined as an implementor of this Interface.

The BinaryTree class does not define the three methods that are in the Collection Interface so BinaryTrees are not Collections (add, remove, contains).

Page 16: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

16

Cursors in Binary TreesCursors in Binary Trees

Cursor operations are provided in the BinaryTree class to traverse the structure.

Cursor operations allow the cursor to move off the tree (this is unusual).

To insert a new node, you must move the cursor off the tree in the location where you want a new node and then invoke the insert method.

Page 17: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

17

Binary Tree Class - Binary Tree Class - interface 1interface 1

public class BinaryTree {

public BinaryTree ();//post: initializes an empty Binary Tree.

public void clear () {// post: removes all nodes from the tree.

public void insert (Object anObject) {// pre: cursor is invalid and not off the top of a non-empty tree// post: if tree is empty, object is inserted at root. Otherwise,

// object is inserted where cursor last moved off tree.

public Object remove () {// pre: cursor is valid and node has no children.// post: leaf is removed; cursor moved to parent, if any// and object is returned.

code based on Bailey pg. 190

Page 18: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

18

Binary Tree Class - Binary Tree Class - interface 2interface 2

public Object value () {// pre: cursor is valid// post: returns the element at the current node

public void setValue (Object anObject) {// pre: cursor is valid// post: sets the current node element to the given object.

public void reset () {// post: moves the cursor to the root node, if any.

public boolean valid () {// post: returns true iff the cursor is on a node

public boolean hasLeft () {// post: returns true iff the cursor is valid and the // current node has a left child

code based on Bailey pg. 190

Page 19: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

19

Binary Tree Class - Binary Tree Class - interface 3interface 3

public boolean isLeftChild () {// post: returns true iff the cursor is valid, has a parent// and is a left child

public void moveLeft () {// pre: cursor is valid// post: moves the cursor to the left child of the current

// node or off the tree if no left child exists.

public void moveUp () {// pre: cursor is valid// post: moves the cursor to the parent of the current

// node or off the tree if there is no parent.

public boolean isEmpty () {// post: returns true iff the tree has no nodes

code based on Bailey pg. 191

Page 20: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

20

Binary Tree Class - Binary Tree Class - interface 4interface 4

public int size () {// post: returns the number of nodes in the tree

public Iterator elements () {// post: returns an Iterator that will perform an inorder // traversal of the tree.

}

code based on Bailey pg. 191

Page 21: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

21

Binary Tree - Binary Tree - Expression EvaluationExpression Evaluation

Binary Trees are often used to hold and evaluate expressions.

For example, here is the parsed form of the expression: (2+3) * 4 / (6-1)

*

+

2 3

4

-

/

6 1

What do the leaf nodesrepresent? The internalnodes?

Page 22: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

22

Notation - tree traversalNotation - tree traversal

*

+

2 3

4

-

/

6 1

Tree Traversal Orders:

prefix order: <operator, left operand, right operand>example: / * + 2 3 4 - 6 1infix order: <left operand, operator, right operand>example: 2 + 3 * 4 / 6 - 1

postfix order: <left operand, right operand, operator>example: 2 3 + 4 * 6 1 - /

Shows post ordertraversal

Page 23: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

23

BinaryTree Example - BinaryTree Example - main()main()

public static void main (String args[ ]) {

/* A Binary Expression Tree. */

BinaryTree tree;

Int value;

tree = constructTree();

System.out.println(tree);

value = evaluateTree(tree);

System.out.println(value);

}

code based on Bailey pg. 192

Page 24: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

24

BinaryTree Example -BinaryTree Example - constructTree()constructTree()private static BinaryTree constructTree() {// post: return a new example expression as a tree.BinaryTree tree;tree = new BinaryTree();tree.insert(new Operator("/"));tree.moveLeft(); tree.insert(new Operator(”*"));tree.moveLeft(); tree.insert(new Operator("+"));tree.moveLeft(); tree.insert(new Integer(2));tree.moveUp();tree.moveRight(); tree.insert(new Integer(3));tree.moveUp(); tree.moveUp();tree.moveRight(); tree.insert(new Integer(4));tree.reset();tree.moveRight(); tree.insert(new Operator("-"));tree.moveLeft(); tree.insert(new Integer(6));tree.moveUp();tree.moveRight(); tree.insert(new Integer(1));return tree;}

code based on Bailey pg. 192

tree

/

*

+

2

4

3

-

6 1

Tree is constructed in preorder, inorder or postorder?

Page 25: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

25

BinaryTree Example -BinaryTree Example - evaluateTree() 1evaluateTree() 1

private static Integer evaluateTree (BinaryTree tree) {// post: return the value of the given Tree.

Iterator iterator;Stack stack;Object element;Integer left;Integer right;Integer result;

iterator = tree.postorderElements ();stack = new StackVector();

code based on Bailey pg. 192

left result right

stack

2 3 + 4 * 6 1 - /

Page 26: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

26

BinaryTree Example -BinaryTree Example - evaluateTree() 2evaluateTree() 2

while (iterator.hasMoreElements()) { element = iterator.nextElement(); System.out.println("Element is: " + element); if (element instanceof Operator) {

right = (Integer) stack.pop(); // get right operand

left = (Integer) stack.pop(); // get left operand

result = ((Operator) element).apply(left, right);stack.push(result);System.out.println("result = " + result);

} else stack.push(element);}return (Integer) stack.pop();

}

code based on Bailey pg. 192

2 3 + 4 * 6 1 - /

2

3

5204

4 6

1

5

Page 27: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

27

Class OperatorClass Operator - State and Constructor- State and Constructorpublic class Operator {

protected String name;

public Operator(String name) {// pre: name is one of: "+" or "-" or "*" or "/".// post: initialize the Expression to have the given name

Assert.pre(name.equals("+") || name.equals("-") ||name.equals("*") || name.equals("/"),"Operator is valid");

this.name = name;}

public String toString() {// post: return a String representation of me.

return this.name;}

code based on Bailey pg. 192

Page 28: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

28

Class Operator - Class Operator - apply()apply()

public Integer apply(Integer left, Integer right) {// post: returns the Integer result of applying the // operator to the two Integers.

if (this.name.equals("+")) return new Integer(left.intValue() + right.intValue());else if (this.name.equals("-")) return new Integer(left.intValue() - right.intValue());else if (this.name.equals("*")) return new Integer(left.intValue() * right.intValue());else // divide return new Integer(left.intValue() / right.intValue());

}

}

code based on Bailey pg. 192

Page 29: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

29

BinaryTree Example - BinaryTree Example - outputoutput

<BinaryTree: (/ (* (+ 2 3) 4) (- 6 1))>Element is: 2Element is: 3Element is: +result = 5Element is: 4Element is: *result = 20Element is: 6Element is: 1Element is: -result = 5Element is: /result = 44

Page 30: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

30

Binary Tree NodeBinary Tree Node

To implement the Binary Tree class, we introduce a BinaryTreeNode.

datarightleft

parent

Page 31: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

31

BinaryTreeNodeBinaryTreeNode - - state and Constructorstate and Constructor

public class BinaryTreeNode {protected Object data;protected BinaryTreeNode parent;protected BinaryTreeNode left;protected BinaryTreeNode right;

public BinaryTreeNode(Object anObject) {// post: initializes the BinaryTreeNode to hold the given// object and to have two null sub-trees.

this.data = anObject;this.left = null;this.right = null;this.parent = null;}

code based on Bailey pg. 194

Page 32: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

32

BinaryTreeNode -BinaryTreeNode - Constructor and AccessConstructor and Access

public BinaryTreeNode(Object anObject, left BinaryTreeNode, right BinaryTreeNode) {// post: initializes the BinaryTreeNode to hold the given// object and to have the given Nodes as sub-trees.

this(anObject);this.setLeft(left);this.setRight(right);

}

public Object value() {// post: return the data for this node.

return this.data;}

code based on Bailey pg. 197

Page 33: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

33

BinaryTreeNode - BinaryTreeNode - Access and SettingAccess and Setting

public BinaryTreeNode left() {// post: return the left sub-tree.

return this.left;}

public BinaryTreeNode parent() {// post: return the parent node.

return this.parent;}

public void setValue(Object anObject) {// post: set the data in this node to be the given object.

this.data = anObject;}

code based on Bailey pg. 197

right()is similar

Page 34: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

34

BinaryTreeNode - BinaryTreeNode - SettingSetting

public void setParent(BinaryTreeNode aNode) {// post: set the parent node to be the given node.

this.parent = aNode;}

public void setLeft(BinaryTreeNode aNode) {// post: set the left sub-tree to be the given node.

if (this.left != null && (this.left.parent() == this)) this.left.setParent(null);this.left = aNode;if (this.left != null) this.left.setParent(this);

}

code based on Bailey pg. 196

setRight(BinaryTreeNode)is similar

datarightleft

parent datarightleft

parent

datarightleft

parent

aNode

this

null

Page 35: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

35

BinaryTreeNode - BinaryTreeNode - TestingTesting

public boolean isLeftChild() {// post: returns true if this node is the left child of its// parent.

if (this.parent == null) return false;return this == this.parent.left();

}

code based on Bailey pg. 195

isRightChild()is similar

Page 36: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

36

Binary TreeBinary Tree

A Binary Tree consists of a root node, two cursors (a current node and a prior node), a last movement direction indicator and the cached tree size.

cursorroot

priorwentLeft

size

Page 37: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

37

Binary Tree - Binary Tree - state and constructorstate and constructor

public class BinaryTree {protected BinaryTreeNode root;protected BinaryTreeNode cursor;protected BinaryTreeNode prior;protected boolean wentLeft;protected int size;

public BinaryTree();//post: initializes an empty Binary Tree.

this.clear();}

code based on Bailey pg. 198

Page 38: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

38

Binary Tree - Binary Tree - clear() and value()clear() and value()

public void clear() {// post: removes all nodes from the tree.

this.root = null;this.cursor = null;this.prior = null;this.wentLeft = false;this.size = 0;

}public Object value() {// pre: cursor is valid// post: returns the element at the current node

Assert.pre(this.valid(), “Cursor is valid.”);return this.cursor.value();

}

code based on Bailey pg. 198

Page 39: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

39

Binary Tree -Binary Tree - setValue(Object) and reset()setValue(Object) and reset()

public void setValue(Object anObject) {// pre: cursor is valid// post: sets the current node element to the given object.

Assert.pre(this.valid(), “Cursor is valid.”);this.cursor.setValue(anObject);

}

public void reset() {// post: moves the cursor to the root node, if any.

this.cursor = this.root;this.prior = null;this.wentLeft = false;

}

code based on Bailey pg. 198

Page 40: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

40

Binary TreeBinary Tree - valid(), hasLeft(), isLeftChild()- valid(), hasLeft(), isLeftChild()

public boolean valid() {// post: returns true iff the cursor is on a node

return this.cursor != null;}

public boolean hasLeft() {// post: returns true iff the cursor is valid and the // current node has a left child

return this.valid() && (this.cursor.left() != null);}

public boolean isLeftChild() {// post: returns true iff the cursor is valid, has a parent// and is a left child

return this.valid() && this.cursor.isLeftChild();}

code based on Bailey pg. 198

Page 41: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

41

Binary Tree - Binary Tree - move methodsmove methods

public void moveLeft() {// pre: cursor is valid// post: moves the cursor to the left child of the current// node or off the tree if no left child exists.

Assert.pre(this.valid());this.prior = this.cursor;this.wentLeft = true;this.cursor = this.cursor.left();

}

code based on Bailey pg. 199

Page 42: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

42

Binary Tree - Binary Tree - move methodsmove methods

public void moveUp() {// pre: cursor is valid// post: moves the cursor to the parent of the current// node or off the tree if there is no parent.

Assert.pre(this.valid());this.prior = null;this.cursor = this.cursor.parent();

}

code based on Bailey pg. 199

Page 43: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

43

Binary Tree - Binary Tree - isEmpty(), size()isEmpty(), size()

public boolean isEmpty() {// post: returns true iff the tree has no nodes

return this.size == 0;}

public int size() {// post: returns the number of nodes in the tree

return this.size;}

code based on Bailey pg. 191

Page 44: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

44

Binary Tree InsertionBinary Tree Insertion

There are three cases:– add to an empty tree– add a left child– add a right child

datarightleft

parent

cursorroot

priorwentLeft true

size 8 9

datarightleft

parent

datarightleft

parent

cursorroot

priorwentLeft false

size 8 9

datarightleft

parent

datarightleft

parent

cursorroot

priorwentLeftsize 0 1

null

Page 45: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

45

Binary Tree - Binary Tree - insert(Object)insert(Object)

public void insert(Object anObject) {// pre: cursor is invalid and not off top of a non-empty tree// post: if tree is empty, object is inserted at root// Otherwise, object is inserted where cursor last moved off

Assert.pre(this.cursor == null, “Insertion does not overwrite node”);if (this.prior == null){

Assert.pre(this.root == null, “Insertion at root only in empty tree”);this.root = new BinaryTreeNode(anObject);this.cursor = this.root;}

else {this.cursor = new BinaryTreeNode(anObject);if (this.wentLeft) { this.prior.setLeft(this.cursor);else this.prior.setRight(this.cursor);

}this.size++; }

code based on Bailey pg. 200

Page 46: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

46

Binary Tree RemovalBinary Tree Removal

There are three cases:– remove root – remove left child– remove right child

cursorroot

priorwentLeftsize 1 0

datarightleft

parent

null

cursorroot

priorwentLeft true

size 9 8

datarightleft

parent

datarightleft

parentnull

cursorroot

priorwentLeft false

size 9 8

datarightleft

parent

datarightleft

parentnull

Page 47: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

47

Binary Tree - Binary Tree - remove() 1remove() 1

public Object remove() {// pre: cursor is valid and node has no children.// post: leaf is removed; cursor moved to parent, if any// and object is returned

Object current;Assert.pre(this.cursor != null, “Node to be removed exists”);Assert.pre(!(this.hasLeft() || this.hasRight()),

“Node to be removed is a leaf”);current = cursor.value();if (this.isLeftChild()) {

this.moveUp();this.cursor.setLeft(null);

}else if (this.isRightChild()) {

this.moveUp();this.cursor.setRight(null);

}

code based on Bailey pg. 200

Page 48: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

48

Binary Tree - Binary Tree - remove() 2remove() 2

else { //remove the root nodethis.root = null;this.cursor = null;this.prior = null;

}this.size- -;return current;

}

public Iterator elements() {// post: returns an Iterator that will perform an inorder // traversal of the tree.

return this.inorderElements(); // later!}}

code based on Bailey pg. 200

Page 49: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

49

Binary Tree TraversalsBinary Tree Traversals

There are four common binary tree traversals:– Preorder: visit node then left then right– Inorder: left then visit node then right– Postorder: left then right then visit node– Levelorder: visit nodes of level i, before visiting

nodes of level i + 1

Page 50: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

50

Binary Tree Traversal ExampleBinary Tree Traversal Example

Preorder: / * + 2 3 4 - 6 1 <node,leftst,rightst> Inorder: 2 + 3 * 4 / 6 - 1 <leftst,node,rightst> Postorder: 2 3 + 4 * 6 1 - / <leftst,rightst,node> Levelorder: / * - + 4 6 1 2 3 <children set>*

*

+

2 3

4

-

/

6 1

Page 51: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

51

Binary Tree IteratorsBinary Tree Iterators

There is one Iterator class for each kind of traversal.

The code is similar for each class, except for the reset() and nextElement() methods.

Page 52: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

52

BTPreorderIterator - state and constructorBTPreorderIterator - state and constructor

public class BTPreorderIterator implements Iterator {protected BinaryTreeNode root;protected Stack todo;

public BTPreorderIterator(BinaryTreeNode root);//post: initializes the iterator to traverse in preorder.

this.root = root;this.todo = new StackList();this.reset();

}

code based on Bailey pg. 203

Page 53: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

53

BTPreorderIteratorBTPreorderIterator - - state and constructorstate and constructor

public void reset();//post: resets the iterator to traverse again.

this.todo.clear(); //clear the stack to set up

// new traversal.if (this.root != null) this.todo.push(this.root);

}

code based on Bailey pg. 203

Page 54: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

54

BTPreorderIterator - BTPreorderIterator - methods 1methods 1

public boolean hasMoreElements();//post: return true iff iterator is not finished.

return !this.todo.isEmpty();}

public Object value();//pre: hasMoreElements()//post: returns the current element.

return ((BinaryTreeNode)this.todo.peek()).value();}

code based on Bailey pg. 203

Page 55: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

55

BTPreorderIterator - BTPreorderIterator - nextElement()nextElement()

public Object nextElement();//pre: hasMoreElements()//post: returns the next element, increments the iterator.

BinaryTreeNode old;Object result;old = (BinaryTreeNode) this.todo.pop();result = old.value();if (old.right() != null) this.todo().push(old.right());if (old.left() != null) this.todo().push(old.left());return result;

}}

code based on Bailey pg. 204

A

B E

C D F

todo

reset,{nextElement}*

@A@E

@B@D

@C

@F

Page 56: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

56

BTInorderIterator - state and constructorBTInorderIterator - state and constructor

public void reset();//post: resets the iterator to traverse again.

BinaryTreeNode current;this.todo.clear();current = this.root; while (current != null){//push all left nodes on the stack

this.todo.push(current); current = current.left();}

}

code based on Bailey pg. 205

A

B E

C D F

Page 57: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

57

BTInorderIterator - BTInorderIterator - nextElement()nextElement()

public Object nextElement();//pre: hasMoreElements()//post: returns the next element, increments the iterator.

BinaryTreeNode old;BinaryTreeNode current; Object result;

old = (BinaryTreeNode) this.todo.pop();result = old.value();current = old.right();while (current != null) { //push right node and all its this.todo.push(current) //left children on the stack current = current.left();}return result;

}

code based on Bailey pg. 205

A

B E

C D F

J K

successor of

Page 58: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

58

Property-based methodsProperty-based methods The textbook makes all of the property-based methods

static and puts them in the BinaryTreeNode class.

It uses a BinaryTreeNode as an argument instead of a tree.

Sometimes the argument is treated as the root node of a sub-tree for which the property is desired.

Most of these methods are implemented recursively.

We will use the fact that a full tree has 2h+1 - 1 nodes, where h is the height.

Page 59: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

59

BinaryTreeNode - BinaryTreeNode - static methods 1static methods 1public static BinaryTreeNode root(BinaryTreeNode aNode) {//post: returns the root of the tree that contains the given node.

if ((aNode == null) || (aNode.parent() == null)) return aNode;else return root(aNode.parent());

}

public static int depth(BinaryTreeNode aNode) {//post: returns the depth of the given node in its tree.

if (aNode == null) return -1;else return 1 + depth(aNode.parent());

}

code based on Bailey pg. 211

WC: O(log(n)) wheren = number of nodes

WC: O(log(n))

Page 60: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

60

BinaryTreeNode - BinaryTreeNode - static methods 2static methods 2

public static int height(BinaryTreeNode aNode) {//post: returns the height of the given node in its tree.

if (aNode == null) return -1;else return 1 + Math.max(height(aNode.left()),

height(aNode.right()));}

public static boolean isFull(BinaryTreeNode aNode) {//post: returns true iff subtree rooted at the node full.

if (aNode == null) return true;if (height(aNode.left()) != height(aNode.right())) return false;return isFull(aNode.left()) &&

isFull(aNode.right());}

code based on Bailey pg. 211

WC: O(n*log(n))

WC: O(log(n))

Read text foran O(n) algorithm

Page 61: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

61

BinaryTreeNode - BinaryTreeNode - static methods 3static methods 3

public static int size(BinaryTreeNode aNode) {//post: returns the size of the subtree rooted at node.

if (aNode == null) return 0;else return 1 + size(aNode.left()) + size(aNode.right());

}

code based on Bailey pg. 213

WC: O(n)

Page 62: Trees Cmput 115 - Lecture 22 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from

©Duane Szafron 2000

62

Some Principles from the TextbookSome Principles from the Textbook

19. Don’t let opposing references show through the interface.

20. Use wrappers to provide a consistent interface to recursive structures.

21. Write methods to be as general as possible.

principles from Bailey ch. 10