Vous êtes sur la page 1sur 29

Trees Page 1

BFH-TI: Softwareschule Schweiz

Algorithms and Data Structures


Trees

Dr. Rolf Haenni

CAS SD04

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Page 2

Outline

Trees

Tree Traversal

Binary Trees

Implementing Trees

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Trees Page 3

Outline

Trees

Tree Traversal

Binary Trees

Implementing Trees

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Trees Page 4

What is a Tree?
I In mathematics and computer science, a tree is an abstract
model of a hierarchical structure
I A tree consists of a set of connected nodes with a parent-child
relation
I Trees are special cases of connected graphs with no cycles
(there is unique path between any two nodes)
I A disconnected tree, i.e. a set of trees, is called forest
I Trees are usually depicted upside down, with the root on top
I Applications:
Ý File systems
Ý Organization charts
Ý Class hierarchy in OOP
Ý Structured documents (section, subsection, etc.)

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Trees Page 5

Tree, Forest, Graph

Tree Forest Graph

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Trees Page 6

Example: File System Tree


518K
classes07/
1K

196K 253K
algdata/ xyz webprog/
1K 68K 1K

16K 171K 195K


xyz homeworks/ slides/ xyz project/
8K 1K 1K 57K 1K

129K 65K
hw1 hw2 hw3 hw4 sl1 sl2 sl3 papers/ demos/
3K 2K 5K 5K 64K 32K 74K 1K 1K

p1 p1 xyz
32K 96K 64K

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Trees Page 7

Tree Terminology
Root: Node without parent (A)
Internal Node: Node with at least one child
(A,B,C,G)
A 0
External Node: Node without children (leaf)
(E,F,I,J,K,H,D)
B C D 1
Descendant: Children, grandchildren, . . .
Ancestors: Parent, grandparent, . . . E F G H 2
Size: Number of nodes (11)
Depth: Number of ancestors I J K 3

Height: Maximum depth (3)


Subtree: Tree consisting of a node and
its descendants

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Trees Page 8

Tree ADT
I We use positions to abstract nodes (see list ADT)
I General operations:
Ý size(): returns the number of nodes
Ý height(): returns the height of the tree
Ý isEmpty(): indicates whether the tree is empty
Ý elements(): returns an iterator over all elements
Ý positions(): returns an iterator over all positions
I Accessors:
Ý root(): returns the root node (if it exists)
Ý parent(p): returns the parent of node p (if it exists)
Ý children(p): returns an iterator over all children of p
Ý descendants(p): returns an iterator over all descendants of p
Ý ancestors(p): returns an iterator over all ancestors of p

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Trees Page 9

Tree ADT (cont.)

I Query Operations:
Ý isRoot(p): indicates whether p is a root
Ý isInternal(p): indicates whether p is an internal node
Ý isExternal(p): indicates whether p is an external node
Ý depth(p): returns the depth of node p
I Update Operations:
Ý addRoot(e): adds a root which stores e to an empty tree
Ý insertChild(p,e): inserts a new child for p which stores e
Ý replaceElement(p,e): stores e at node p
Ý swapElements(p,q): swaps the elements stored at p and q
I Further update operations (e.g. for removing nodes) may be
added on request

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Trees Page 10

Algorithm for Depth

Recursive solution in pseudo-code:

Algorithm depth(p) // runs in O(depth(p)) time


if isRoot(p) then
return 0
else
return 1 + depth(parent(p))

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Trees Page 11

Algorithm for Height

Recursive solution in pseudo-code:

Algorithm height()
return heightOf(root())

Algorithm heightOf(p) // runs in O(size()) time


if isExternal(p) then
return 0
else
h←0
foreach q in children(p) do // short form for using the iterator
h ← max(h , heightOf(q))
return h + 1

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Tree Traversal Page 12

Outline

Trees

Tree Traversal

Binary Trees

Implementing Trees

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Tree Traversal Page 13

Postorder Traversal

I A traversal visits the nodes of a tree in a systematic manner


I In a postorder traversal, a node is visited after its descendants

11
Algorithm postOrder(p)
3 9 10
foreach q in children(p) do
postOrder(q) 1 2 7 8
visit(p)
4 5 6

I Visiting a node with visit(p) could be any sort of operation


related to node p or its element
I Initial call: postOrder(root())

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Tree Traversal Page 14

Preorder Traversal

I In a preorder traversal, a node is visited before its descendants


1
Algorithm preOrder(p)
2 5 11
visit(p)
foreach q in children(p) do 3 4 6 10
preOrder(q)
7 8 9

I Initial call: preOrder(root())


I Application: print a structured document

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Binary Trees Page 15

Outline

Trees

Tree Traversal

Binary Trees

Implementing Trees

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Binary Trees Page 16

Binary Tree
I A binary tree is a tree with the following properties:
Ý Each internal node has at most two children
Ý The children of a node are an ordered pair
I The children of an internal node are called left and right child
I Alternative recursive definition: a binary tree is either
Ý a single node called root, or
Ý a tree whose root has an ordered pair of children, each of
which is a binary tree
I Applications:
Ý Arithmetic expressions
Ý Decision trees
Ý Searching

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Binary Trees Page 17

Proper Binary Tree

I A binary tree is a called proper, if all


internal nodes have exactly 2 children
I Notation:
n number of nodes
e number of external nodes
i number of internal nodes
h height
I Properties:
Ý e =i +1
Ý n = e + i = 2i + 1 = 2e − 1
Ý 2h + 1 ≤ n ≤ 2h+1 − 1
Ý log(n + 1) − 1 ≤ h ≤ n−1
2

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Binary Trees Page 18

Binary Tree ADT


I The binary tree ADT extends the tree ADT, i.e. it inherits all
its operations
I Additional operations:
Ý hasLeft(p): checks whether p has a left child
Ý hasRight(p): checks whether p has a right child
Ý leftChild(p): returns the left child of p (if it exists)
Ý rightChild(p): returns the right child of p (if it exists)
Ý sibling(p): returns the sibling of p (if it exists)
I Typical update operations:
Ý insertLeft(p,e): adds a left child to p (unless it exists)
Ý insertRight(p,e): adds a right child to p (unless it exists)
Ý remove(p): removes p (unless it has 2 children)
Ý attach(p,t1,t2): connects two subtrees t1 and t2 at node p

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Binary Trees Page 19

Binary Tree ADT (cont.)

I Typical update operations for proper binary trees:


Ý insertChildren(p,e1,e2): adds a left and a right child to p
Ý removeParent(p): removes node p together with its parent
Ý removeChildren(p): removes the left and right child of p,
thus making it an external node

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Binary Trees Page 20

Inorder Traversal
I In a inorder traversal, a node is visited after its left subtree
and before its right subtree

Algorithm inOrder(p) 4
if hasLeft(p) then
2 8
inOrder(leftChild(p))
visit(p) 1 3 6 9
if hasRight(p) then
5 7
inOrder(rightChild(p))

I Application: draw a binary tree at coordinates x(p) and y (p)


Ý x(p) = inorder rank of p
Ý y (p) = depth of p

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Binary Trees Page 21

Euler Tour Traversal

I The Euler Tour traversal is a generic traversal of binary trees


I Includes preorder, postorder, and inorder traverals as special
cases
I The idea is to walk around the tree and visit each internal
node three times:
Ý on the left (preorder)
Ý from below (inorder)
Ý on the right (postorder)
I Visit each external node once

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Binary Trees Page 22

Euler Tour Traversal (cont.)

Algorithm eulerTour(p)
if isExternal(p) then L R
visitExternal(p) B
else
L R L R
visitLeft(p)
B B
if hasLeft(p) then
eulerTour(leftChild(p)) L R
visitBelow(p) E E B E
if hasRight(p) then
eulerTour(rightChild(p))
E E
visitRight(p)

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Implementing Trees Page 23

Outline

Trees

Tree Traversal

Binary Trees

Implementing Trees

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Implementing Trees Page 24

Level Numbering
The level number L(p) of a node p in a binary tree is defined as
follows:

1,
 if p is the root of the tree
L(p) = 2·L(q), if p is the left child of node q

2·L(q) + 1, if p is the right child of node q

2 3

4 5 6 7

11 12
8 9 10 13

16 17 20 21 26 27

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Implementing Trees Page 25

Array-Based Implementation

I The level numbering suggests the representation of a binary


tree by means of an array T with T [L(p)] = p
leftChild(p) = T [2·L(p)] parent(p) = T [bL(p)/2c]
rightChild(p) = T [2·L(p) + 1] sibling (p) = T [L(p) ± 1]

I T [0] is unused (alternatively, use indices L(p) − 1)


I Unless the binary tree is complete, the array may have many
empty cells (e.g. 14, 15, 18, 19, 22, 23, 24, 25)
I In the worst case, an array of length N = 2n + 1 is needed,
where n is the number of nodes in the tree (exponential space)
I The array itself should be growable (doubling strategy)

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Implementing Trees Page 26

Array-Based Implementation (cont.)


I Solution 1: A position p contains two fields: its level number
L(p) and the stored element e
1 A B C D Elements
A
2 3 1 2 3 5 Positions
B C

4 5
D null null null null null Array T
0 1 2 3 4 5 6 7 8

I Solution 2: The elements are stored directly in T , and the


array indices L(p) ∈ {1, . . . , n} play the role of the positions
null A B C null D null null null Array T
0 1 2 3 4 5 6 7 8 Positions

Strictly speaking: positions are pairs p = (T , L(p))

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Implementing Trees Page 27

Linked Structure Implementation


I A node (position) of a binary tree is a record storing
Ý Element
Ý Link to parent node
Ý Link to left child
Ý Link to right child

B C A

D E B C

D E

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Implementing Trees Page 28

Linked Structure for General Trees


I A position (node) of a general tree is a record storing
Ý Element
Ý Link to parent node
Ý List of children
(e.g. singly-linked)

A A

C
B C

B
D E F

D E F

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures
Trees Implementing Trees Page 29

UML Diagram

<<interface>> <<interface>> <<interface>> <<interface>>


Tree BasicCollection Position Iterator
etc. isEmpty() element() etc.
site()

<<interface>> <<interface>>
BinaryTree List
etc. etc.

LinkedTree ArrayBinaryTree TreeNode ArrayTreeNode


root: TreeNode T: Array element: Object T: Array
n: Integer n: Integer parent: TreeNode L: Integer
children: List

LinkedBinaryTree LinkedList BinaryTreeNode ListNode


root: BinaryTreeNode first: ListNode element: Object element: Object
n: Integer n: Integer parent: BinaryTreeNode next: ListNode
left: BinaryTreeNode
right: BinaryTreeNode

Berner Fachhochschule Rolf Haenni


Technik und Informatik Algorithms and Data Structures

Vous aimerez peut-être aussi