• Tidak ada hasil yang ditemukan

PDF Data structure and algorithm in Python - Tree

N/A
N/A
Protected

Academic year: 2023

Membagikan "PDF Data structure and algorithm in Python - Tree"

Copied!
114
0
0

Teks penuh

(1)

Data structure and algorithm in Python

Tree

Seongjin Lee

Dept of Aerospace and Software Engineering, Gyeongsang National University

(2)

Table of contents

1. General Trees 2. Binary Tree 3. Implementing Trees 4. Tree Traversal Algorithms 5. Expression Tree

(3)

General Trees

(4)

General Trees

Tree is one of the most important nonlinear data structures.

• Tree structures are indeed a breakthrough in data organization, for they allow us to implement a host of algorithms much faster than when using linear data structures, such as array-based lists or linked lists.

• Trees also provide a natural organization for data, and consequently have become ubiquitous structures in file systems, graphical user interfaces, databases, Web sites, and other computer systems.

(5)

General Trees

When we say that trees are “nonlinear”, we are referring to an organizational relationship that is richer than the simple“before” and

“after”relationships between objects in sequences. The relationships in a tree arehierarchical, with some objects being“above”and some “below”

others.

3

(6)

General Trees

Actually, the main terminology for tree data structures comes from family trees, with the terms “parent”, “child”, “ancestor” and “descendant”

being the most common words used to describe rela- tionships.

(7)

General Trees

Tree Definitions and Properties

(8)

Tree Definitions and Properties

A tree is an abstract data type that stores elements hierarchically.

With the exception of the top element, each element in a tree has a parent element and zero or more children elements.

We typically call the top element the root of the tree, but it is drawn as the highest element, with the other elements being connected below.

(9)

Tree Definitions and Properties

6

(10)

Tree Definitions and Properties

Definition : Formal Tree Definition

A treeT is a set of nodes storing elements such that the nodes have a parent-child relationship that satisfies the following properties:

• IfT is nonempty, it has a special node, called the root of T , that has no parent.

• Each node v ofT different from the root has a unique parent nodew; every node with parent w is a child ofw.

(11)

Tree Definitions and Properties

According to the definition, a tree can be empty, meaning that it does not have any nodes. This convention also allows us to define a tree recursively such that a treeT is either empty or consists of a noder, called the root ofT, and a (possibly empty) set of subtrees whose roots are the children ofr.

8

(12)

Tree Definitions and Properties

• Two nodes that are children of the same parent are siblings.

• A nodev is external ifv has no children.

• A nodev is internal if it has one or more children. External nodes are also known as leaves.

• A nodeu is an ancestor of a nodev ifu=v oruis an ancestor of the parent of v.

Conversely, we say that a nodev is a descendant of a nodeu ifuis an ancestor of v.

• The subtree of T rooted at a nodev is the tree consisting of all the descendants ofv inT (includingv itself).

(13)

Tree Definitions and Properties

10

(14)

General Trees

• An edge of treeT is a pair of nodes(u,v)such thatu is the parent ofv, or vice versa.

• A path ofT is a sequence of nodes such that any two consecutive nodes in the sequence form an edge.

(15)

Tree Definitions and Properties

12

(16)

Tree Definitions and Properties

(17)

Tree Definitions and Properties

Definition : Ordered Tree

A tree is ordered if there is a meaningful linear order among the children of each node; that is, we purposefully identify the children of a node as being the first, second, third, and so on. Such an order is usually visualized by arranging siblings left to right, according to their order.

14

(18)

Tree Definitions and Properties

(19)

General Trees

The Tree Abstract Data Type

(20)

The Tree Abstract Data Type

We define a tree ADT using the concept of a position as an abstraction for a node of a tree. An element is stored at each position, and positions satisfy parent-child relationships that define the tree structure.

A position object for a tree supports the method:

• p.element(): Return the element stored at position p.

(21)

The Tree Abstract Data Type

The tree ADT then supports the following accessor methods, allowing a user to navigate the various positions of a tree:

• T.root(): Return the position of the root of treeT orNoneifT is empty.

• T.is_root(p): ReturnTrueif positionpis the root of treeT.

• T.parent(p): Return the position of the parent of positionp, or None ifpis the root ofT.

• T.num_chidren(p): Return the number of children of positionp.

• T.children(p): Generate an iteration of the children of positionp.

• T.is_leaf(): ReturnTrueif positionpdoes not have any chidlren.

17

(22)

The Tree Abstract Data Type

• len(T): Return the number of positions (and hence elements) that are contained in treeT.

• T.is_empty(): ReturnTrueif treeT does not contain any positions.

• T.positions(): Generate an iteration of all positions of T.

• iter(T): Generate an iteration of all elements stored within T.

Any of the above methods that accepts a position as an argument should generate aValueErrorif that position is invalid forT.

(23)

The Tree Abstract Data Type

• len(T): Return the number of positions (and hence elements) that are contained in treeT.

• T.is_empty(): ReturnTrueif treeT does not contain any positions.

• T.positions(): Generate an iteration of all positions of T.

• iter(T): Generate an iteration of all elements stored within T. Any of the above methods that accepts a position as an argument should generate aValueError if that position is invalid forT.

18

(24)

The Tree Abstract Data Type

• IfT is ordered, thenT.chidren(p)reports the chidren ofp in the natural order.

• Ifpis a leaf, thenT.chidren(p) generates an empty iteration.

• IfT is empty, then both T.positions()and anditer(T) generate empty iterations.

(25)

The Tree Abstract Data Type

A formal mechanism to designate the relationships between different implementations of the same abstraction is through the definition of one class that serves as anabstract base class, via inheritance, for one or moreconcrete classes.

We choose to define a Tree class that serves as an abstract base class corresponding to the tree ADT.

20

(26)

The Tree Abstract Data Type

A formal mechanism to designate the relationships between different implementations of the same abstraction is through the definition of one class that serves as anabstract base class, via inheritance, for one or moreconcrete classes.

We choose to define a Tree class that serves as an abstract base class corresponding to the tree ADT.

(27)

The Tree Abstract Data Type

However, ourTreeclass does not define any internal representation for storing a tree, and five of the methods given in that code fragment remain abstract (root,parent,num_children,children, and __len__); each of these methods raises a NotImplementedError.

The subclasses are responsible for overriding abstract methods, such as children, to provide a working implementation for each behavior, based on their chosen internal representation.

With theTreeclass being abstract, there is no reason to create a direct instance of it, nor would such an instance be useful. The class exists to serve as a base for inheritance, and users will create instances of concrete subclasses.

21

(28)

The Tree Abstract Data Type

However, ourTreeclass does not define any internal representation for storing a tree, and five of the methods given in that code fragment remain abstract (root,parent,num_children,children, and __len__); each of these methods raises a NotImplementedError.

The subclasses are responsible for overriding abstract methods, such as children, to provide a working implementation for each behavior, based on their chosen internal representation.

With theTreeclass being abstract, there is no reason to create a direct instance of it, nor would such an instance be useful. The class exists to serve as a base for inheritance, and users will create instances of concrete subclasses.

(29)

The Tree Abstract Data Type

However, ourTreeclass does not define any internal representation for storing a tree, and five of the methods given in that code fragment remain abstract (root,parent,num_children,children, and __len__); each of these methods raises a NotImplementedError.

The subclasses are responsible for overriding abstract methods, such as children, to provide a working implementation for each behavior, based on their chosen internal representation.

With theTreeclass being abstract, there is no reason to create a direct instance of it, nor would such an instance be useful. The class exists to serve as a base for inheritance, and users will create instances of concrete subclasses.

21

(30)

The Tree Abstract Data Type

c l a s s Tr e e :

c l a s s P o s i t i o n : def e l e m e n t ( s e l f ) :

r a i s e N o t I m p l e m e n t e d E r r o r ( ’ m u s t be i m p l e m e n t e d by s u b c l a s s ’ )

def _ _ e q _ _ ( self , o t h e r ) :

r a i s e N o t I m p l e m e n t e d E r r o r ( ’ m u s t be i m p l e m e n t e d by s u b c l a s s ’ )

def _ _ n e _ _ ( self , o t h e r ) : r e t u r n not ( s e l f == o t h e r )

(31)

The Tree Abstract Data Type

def ro o t ( s e l f ) :

r a i s e N o t I m p l e m e n t e d E r r o r ( ’ m u s t be i m p l e m e n t e d by s u b c l a s s ’ )

def p a r e n t ( self , p ) :

r a i s e N o t I m p l e m e n t e d E r r o r ( ’ m u s t be i m p l e m e n t e d by s u b c l a s s ’ )

def n u m _ c h i l d r e n ( self , p ) :

r a i s e N o t I m p l e m e n t e d E r r o r ( ’ m u s t be i m p l e m e n t e d by s u b c l a s s ’ )

def c h i l d r e n ( self , p ) :

r a i s e N o t I m p l e m e n t e d E r r o r ( ’ m u s t be i m p l e m e n t e d by s u b c l a s s ’ )

23

(32)

The Tree Abstract Data Type

def _ _ l e n _ _ ( s e l f ) :

r a i s e N o t I m p l e m e n t e d E r r o r ( ’ m u s t be i m p l e m e n t e d by s u b c l a s s ’ )

def i s _ r o o t ( self , p ) : r e t u r n s e l f . r o o t () == p

def i s _ l e a f ( self , p ) :

r e t u r n s e l f . n u m _ c h i l d r e n ( p ) == 0

def i s _ e m p t y ( s e l f ) : r e t u r n len( s e l f ) == 0

(33)

General Trees

Computing Depth and Height

(34)

Computing Depth and Height

Definition : Depth

Letpbe the position of a node ofT. Thedepthofpis the number of ancestors of p, excludingp itself.

Note that this definition implies that the depth of the root ofT is 0.

(35)

Computing Depth and Height

The depth ofp can also be recursively defined as follows:

• Ifpis the root, then the depth of pis 0.

• Otherwise, the depth ofp is one plus the depth of the pararent ofp.

def d e p t h ( self , p ) : if s e l f . i s _ r o o t ( p ) :

r e t u r n 0 e l s e:

r e t u r n 1 + s e l f . d e p t h ( s e l f . p a r e n t ( p ) )

26

(36)

Computing Depth and Height

The depth ofp can also be recursively defined as follows:

• Ifpis the root, then the depth of pis 0.

• Otherwise, the depth ofp is one plus the depth of the pararent ofp.

def d e p t h ( self , p ) : if s e l f . i s _ r o o t ( p ) :

r e t u r n 0 e l s e:

r e t u r n 1 + s e l f . d e p t h ( s e l f . p a r e n t ( p ) )

(37)

Computing Depth and Height

• The running time ofT.depth(p) for a positionpisO(dp+1), where dp denotes the depth ofp inT.

• T.depth(p) runs inO(n)worst-case time, wherenis the total number of positions ofT, because a position ofT may have depth n1 if all nodes form a single branch.

27

(38)

Computing Depth and Height

Definition : Height

Theheightof a position pin a treeT is also defined recursively:

• Ifpis a leaf,then the height of pis 0.

• Otherwise, the height of pis one more than the maximum of the heights ofp’s children.

The height of a nonempty treeT is the height of the root ofT.

(39)

Computing Depth and Height

Property

The height of a nonempty tree T is equal to the maximum of the depths of its leaf positions.

def _ h e i g h t 1 ( s e l f ) : # O ( n ^2) worst - ca s e ti m e r e t u r n max( s e l f . d e p t h ( p )

for p in s e l f . p o s i t i o n s () if se l f . i s _ l e a f ( p ) )

29

(40)

Computing Depth and Height

Property

The height of a nonempty tree T is equal to the maximum of the depths of its leaf positions.

def _ h e i g h t 1 ( s e l f ) : # O ( n ^2) worst - ca s e ti m e r e t u r n max( s e l f . d e p t h ( p )

for p in s e l f . p o s i t i o n s () if se l f . i s _ l e a f ( p ) )

(41)

Computing Depth and Height

We can compute the height of a tree more efficiently, inO(n)worst-case time, by relying instead on the original recursive definition. To do this, we will parameterize a function based on a position within the tree, and calculate the height of the subtree rooted at that position.

def _ h e i g h t 2 ( self , p ) : # t i m e is l i n e a r in s i z e of s u b t r e e

if s e l f . i s _ l e a f ( p ) : r e t u r n 0

e l s e:

r e t u r n 1 + max( s e l f . _ h e i g h t 2 ( c )

for c in s e l f . c h i l d r e n ( p ) )

30

(42)

Computing Depth and Height

We can compute the height of a tree more efficiently, inO(n)worst-case time, by relying instead on the original recursive definition. To do this, we will parameterize a function based on a position within the tree, and calculate the height of the subtree rooted at that position.

def _ h e i g h t 2 ( self , p ) : # t i m e is l i n e a r in s i z e of s u b t r e e

if s e l f . i s _ l e a f ( p ) : r e t u r n 0

e l s e:

r e t u r n 1 + max( s e l f . _ h e i g h t 2 ( c )

for c in s e l f . c h i l d r e n ( p ) )

(43)

Computing Depth and Height

def h e i g h t ( self , p = N o n e ) : if p is No n e :

p = s e l f . r o o t ()

r e t u r n s e l f . _ h e i g h t 2 ( p )

31

(44)

Binary Tree

(45)

Binary Tree

Definition : Binary Tree

Abinary treeis an ordered tree with following properties:

1. Every node has at most two children.

2. Each child node is labled as being either aleft child or aright child.

3. A left child precedes a right child in the order of children of a node.

• The subtree rooted at a left or right child of an internal nodev is called a left subtreeorright subtree, respectively, ofv.

• A binary tree isproperif each node has either zero or two children. Some people also refer to such trees as beingfullbinary trees. Thus, in a proper binary tree, every internal node has exactly two children. A binary tree that is not proper isimproper.

32

(46)

Binary Tree

Definition : Binary Tree

Abinary treeis an ordered tree with following properties:

1. Every node has at most two children.

2. Each child node is labled as being either aleft child or aright child.

3. A left child precedes a right child in the order of children of a node.

• The subtree rooted at a left or right child of an internal nodev is called a left subtreeorright subtree, respectively, ofv.

• A binary tree isproperif each node has either zero or two children.

Some people also refer to such trees as beingfullbinary trees. Thus, in a proper binary tree, every internal node has exactly two children.

(47)

Binary Tree

33

(48)

Binary Tree

(49)

Binary Tree

Definition : A Recursive Binary Tree Definition Abinary treeis either empty or consists of

1. A noder, called the root ofT, that stores an element 2. A binary tree (possibly empty), called the left subtree of T 3. A binary tree (possibly empty), called the right subtree ofT

35

(50)

Binary Tree

The Binary Tree Abstract Data Type

(51)

The Binary Tree Abstract Data Type

As an abstract data type, a binary tree is a specialization of a tree that supports three additional accessor methods:

• T.left(p): Return the position that represents the left child ofp, or Noneifphas no left child.

• T.right(p): Return the position that represents the right child of p, orNoneifp has no right child.

• T.sibling(p): Return the position that represents the sibling ofp, or Noneifphas no sibling.

36

(52)

The Binary Tree Abstract Data Type

f r o m t r e e i m p o r t T r e e c l a s s B i n a r y T r e e ( T r e e ) :

def le f t ( self , p ) :

r a i s e N o t I m p l e m e n t e d E r r o r ( ’ m u s t be i m p l e m e n t e d by s u b c l a s s ’ )

def r i g h t ( self , p ) :

r a i s e N o t I m p l e m e n t e d E r r o r ( ’ m u s t be i m p l e m e n t e d by s u b c l a s s ’ )

(53)

The Binary Tree Abstract Data Type

def s i b l i n g ( self , p ) : p a r e n t = s e l f . p a r e n t ( p ) if p a r e n t is N o n e :

r e t u r n N o n e e l s e:

if p == s e l f . l e f t ( p a r e n t ) : r e t u r n s e l f . r i g h t ( p a r e n t ) el s e:

r e t u r n s e l f . l e f t ( p a r e n t )

38

(54)

The Binary Tree Abstract Data Type

def c h i l d r e n ( self , p ) :

if s e l f . l e f t ( p ) is not No n e : y i e l d s e l f . l e f t ( p )

if s e l f . r i g h t ( p ) is not N o n e : y i e l d s e l f . r i g h t ( p )

(55)

Binary Tree

Properties of Binary Trees

(56)

Properties of Binary Trees

Binary trees have several interesting properties dealing with relationships between their heights and number of nodes.

We denote the set of all nodes of a treeT at the same depthd as leveld ofT . In a binary tree,

• level 0 has at most one node (the root),

• level 1 has at most two nodes (the children of the root),

• level 2 has at most four nodes,

···

In general, leveld has at most 2d nodes.

(57)

Properties of Binary Trees

41

(58)

Properties of Binary Trees

Property

Let T be a nonempty binary tree, and let n, nE , nI andh denote the number of nodes, number of external nodes, number of internal nodes, and height of T , respectively. Then T has the following properties:

h+1n2h+11

• 1nE2h

hnI2h1

• log(n+1)1hn1

(59)

Properties of Binary Trees

Property : Continue

IfT is proper, thenT has the following properties:

h+1n2h+11

• 1nE2h

hnI2h1

• log(n+1)1hn1

43

(60)

Properties of Binary Trees

Property

In a nonempty proper binary treeT, withnE external nodes andnI internal nodes, we havenE=nI+1.

(61)

Implementing Trees

(62)

Implementing Trees

TheTreeandBinaryTreeclasses that we have defined are both formally abstract base classes.

• Neither of them can be directly instantiated.

• Have not yet defined key implementation details for how a tree will be represented internally, and how we can effectively navigate between parents and children.

• A concrete implementation of a tree must provide methods

• root

• parent

• num_children

• children

• __len__

and in the case of BinaryTree, the additional accessors

• left

(63)

Implementing Trees

Linked Structure for Binary Trees

(64)

Linked Structure for Binary Trees

(65)

Linked Structure for Binary Trees

A natural way to realize a binary treeT is to use a linked structure, with a node that maintains references

• to the element stored at a position p

• to the nodes associated with the children and parent of p.

47

(66)

Linked Structure for Binary Trees

• Ifpis the root ofT, then the parent field ofp isNone.

• Ifpdoes not have a left child (respectively, right child), the associated field isNone.

(67)

Linked Structure for Binary Trees

The tree itself maintains

• an instance variable storing a reference to the root node (if any),

• a variablesizethat represents the overall number of nodes of T.

49

(68)

Operations for Updating a Linked Binary Tree

• T.add_root(e):

Create a root for an empty tree, storing e as the element, and return the position of that root; an error occurs if the tree is not empty.

• T.add_left(p, e):

Create a new node storing element e, link the node as the left child of position p, and return the resulting position; an error occurs if p already has a left child.

• T.add_right(p, e):

Create a new node storing element e, link the node as the right child of position p, and return the resulting position; an error occurs if p already has a right child.

(69)

Operations for Updating a Linked Binary Tree

• T.replace(p, e):

Replace the element stored at position p with element e, and return the previously stored element.

• T.delete(p):

Remove the node at position p, replacing it with its child, if any, and return the element that had been stored at p; an error occurs if p has two children.

• T.attach(p, T1, T2):

Attach the internal structure of trees T1 and T2, respec- tively, as the left and right subtrees of leaf position p of T, and reset T1 and T2 to empty trees; an error condition occurs if p is not a leaf.

51

(70)

Linked Structure for Binary Trees

f r o m b i n a r y _ t r e e i m p o r t B i n a r y T r e e c l a s s L i n k e d B i n a r y T r e e ( B i n a r y T r e e ) :

c l a s s _ N o d e :

_ _ s l o t s _ _ = ’ _ e l e m e n t ’ , ’ _ p a r e n t ’ , ’ _ l e f t ’ ,

’ _ r i g h t ’

def _ _ i n i t _ _ ( self , element , p a r e n t = None , l e f t = None , r i g h t = N o n e ) :

se l f . _ e l e m e n t = e l e m e n t se l f . _ p a r e n t = p a r e n t se l f . _ l e f t = l e f t se l f . _ r i g h t = r i g h t

(71)

Linked Structure for Binary Trees

c l a s s P o s i t i o n ( B i n a r y T r e e . P o s i t i o n ) : def _ _ i n i t _ _ ( self , c o n t a i n e r , n o d e ) :

se l f . _ c o n t a i n e r = c o n t a i n e r se l f . _ n o d e = n o d e

def e l e m e n t ( s e l f ) :

r e t u r n s e l f . _ n o d e . _ e l e m e n t

def _ _ e q _ _ ( self , o t h e r ) :

r e t u r n t y p e( o t h e r ) is t y p e( s e l f ) and o t h e r . _ n o d e is se l f . _ n o d e

53

(72)

Linked Structure for Binary Trees

def _ v a l i d a t e ( self , p ) :

if not i s i n s t a n c e( p , s e l f . P o s i t i o n ) :

r a i s e T y p e E r r o r ( ’ p m u s t be p r o p e r P o s i t i o n t y p e ’ )

if p . _ c o n t a i n e r is not se l f :

r a i s e V a l u e E r r o r ( ’ p d o e s not b e l o n g to th i s c o n t a i n e r ’ )

if p . _ n o d e . _ p a r e n t is p . _ n o d e :

r a i s e V a l u e E r r o r ( ’ p is no l o n g e r v a l i d ’ ) r e t u r n p . _ n o d e

def _ m a k e _ p o s i t i o n ( self , n o d e ) :

r e t u r n s e l f . P o s i t i o n ( self , n o d e ) if n o d e is not No n e e l s e No n e

(73)

Linked Structure for Binary Trees

def _ _ i n i t _ _ ( s e l f ) : s e l f . _ r o o t = N o n e s e l f . _ s i z e = 0

def _ _ l e n _ _ ( s e l f ) : r e t u r n s e l f . _ s i z e

def ro o t ( s e l f ) :

r e t u r n s e l f . _ m a k e _ p o s i t i o n ( s e l f . _ r o o t )

def p a r e n t ( self , p ) :

n o d e = s e l f . _ v a l i d a t e ( p )

r e t u r n s e l f . _ m a k e _ p o s i t i o n ( n o d e . _ p a r e n t )

55

(74)

Linked Structure for Binary Trees

def le f t ( self , p ) :

n o d e = s e l f . _ v a l i d a t e ( p )

r e t u r n s e l f . _ m a k e _ p o s i t i o n ( n o d e . _ l e f t )

def r i g h t ( self , p ) :

n o d e = s e l f . _ v a l i d a t e ( p )

r e t u r n s e l f . _ m a k e _ p o s i t i o n ( n o d e . _ r i g h t )

(75)

Linked Structure for Binary Trees

def n u m _ c h i l d r e n ( self , p ) : n o d e = s e l f . _ v a l i d a t e ( p ) c o u n t = 0

if n o d e . _ l e f t is not No n e : c o u n t += 1

if n o d e . _ r i g h t is not N o n e : c o u n t += 1

r e t u r n c o u n t

57

(76)

Linked Structure for Binary Trees

def _ a d d _ r o o t ( self , e ) : if s e l f . _ r o o t is not No n e :

r a i s e V a l u e E r r o r ( ’ R o o t e x i s t s ’ ) s e l f . _ s i z e = 1

s e l f . _ r o o t = s e l f . _ N o d e ( e )

r e t u r n s e l f . _ m a k e _ p o s i t i o n ( s e l f . _ r o o t )

(77)

Linked Structure for Binary Trees

def _ a d d _ l e f t ( self , p , e ) : n o d e = s e l f . _ v a l i d a t e ( p ) if n o d e . _ l e f t is not No n e :

r a i s e V a l u e E r r o r ( ’ L e f t c h i l d e x i s t s ’ ) s e l f . _ s i z e += 1

n o d e . _ l e f t = s e l f . _ N o d e ( e , n o d e )

r e t u r n s e l f . _ m a k e _ p o s i t i o n ( n o d e . _ l e f t )

59

(78)

Linked Structure for Binary Trees

def _ a d d _ r i g h t ( self , p , e ) : n o d e = s e l f . _ v a l i d a t e ( p ) if n o d e . _ r i g h t is not N o n e :

r a i s e V a l u e E r r o r ( ’ R i g h t c h i l d e x i s t s ’ ) s e l f . _ s i z e += 1

n o d e . _ r i g h t = s e l f . _ N o d e ( e , n o d e )

r e t u r n s e l f . _ m a k e _ p o s i t i o n ( n o d e . _ r i g h t )

(79)

Linked Structure for Binary Trees

def _ r e p l a c e ( self , p , e ) : n o d e = s e l f . _ v a l i d a t e ( p ) old = n o d e . _ e l e m e n t n o d e . _ e l e m e n t = e r e t u r n old

61

(80)

Linked Structure for Binary Trees

def _ d e l e t e ( self , p ) : n o d e = s e l f . _ v a l i d a t e ( p ) if s e l f . n u m _ c h i l d r e n ( p ) == 2:

r a i s e V a l u e E r r o r ( ’ P o s i t i o n has two c h i l d r e n ’ )

c h i l d = n o d e . _ l e f t if n o d e . _ l e f t el s e no d e . _ r i g h t

if c h i l d is not No n e :

c h i l d . _ p a r e n t = n o d e . _ p a r e n t

(81)

Linked Structure for Binary Trees

if n o d e is s e l f . _ r o o t : se l f . _ r o o t = c h i l d e l s e:

p a r e n t = n o d e . _ p a r e n t if n o d e is p a r e n t . _ l e f t :

p a r e n t . _ l e f t = c h i l d el s e:

p a r e n t . _ r i g h t = c h i l d

63

(82)

Linked Structure for Binary Trees

def _ a t t a c h ( self , p , t1 , t2 ) : n o d e = s e l f . _ v a l i d a t e ( p ) if not s e l f . i s _ l e a f ( p ) :

r a i s e V a l u e E r r o r ( ’ p o s i t i o n m u s t be l e a f ’ ) if not t y p e( s e l f ) is ty p e( t1 ) is ty p e( t2 ) :

r a i s e T y p e E r r o r ( ’ T r e e t y p e s m u s t m a t c h ’ ) s e l f . _ s i z e += len( t1 ) + len( t2 )

if not t1 . i s _ e m p t y () : t1 . _ r o o t . _ p a r e n t = n o d e no d e . _ l e f t = t1 . _ r o o t t1 . _ r o o t = N o n e

t1 . _ s i z e = 0

if not t2 . i s _ e m p t y () : t2 . _ r o o t . _ p a r e n t = n o d e

(83)

Implementing Trees

Linked Structure for General Trees

(84)

Linked Structure for General Trees

When representing a binary tree with a linked structure, each node explicitly maintains fields left and right as references to individual children.

For a general tree, there is no a priori limit on the number of children that a node may have.

A natural way to realize a general tree T as a linked structure is to have each node store a single container of references to its children.

(85)

Linked Structure for General Trees

When representing a binary tree with a linked structure, each node explicitly maintains fields left and right as references to individual children.

For a general tree, there is no a priori limit on the number of children that a node may have.

A natural way to realize a general tree T as a linked structure is to have each node store a single container of references to its children.

65

(86)

Linked Structure for General Trees

(87)

Linked Structure for General Trees

67

(88)

Tree Traversal Algorithms

(89)

Tree Traversal Algorithms

A traversal of a tree T is a systematic way of accessing, or “visiting”, all the positions of T .

The specific action associated with the “visit” of a position p depends on the application of this traversal, and could involve anything from

increment- ing a counter to performing some complex computation for p.

68

(90)

Tree Traversal Algorithms

Preorder and Postorder Traversals of General Trees

(91)

Preorder and Postorder Traversals of General Trees

In apreorder traversalof a tree T, the root of T is visited first and then the subtrees rooted at its children are traversed recursively. If the tree is ordered, then the subtrees are traversed according to the order of the children.

69

(92)

Preorder and Postorder Traversals of General Trees

c l a s s Tr e e :

def p r e o r d e r ( s e l f ) :

if not s e l f . i s _ e m p t y () :

for p in s e l f . _ s u b t r e e _ p r e o r d e r ( s e l f . r o o t () ) :

y i e l d p

def _ s u b t r e e _ p r e o r d e r ( self , p ) : y i e l d p

for c in s e l f . c h i l d r e n ( p ) :

for o t h e r in s e l f . _ s u b t r e e _ p r e o r d e r ( c ) : y i e l d o t h e r

(93)

Preorder and Postorder Traversals of General Trees

c l a s s Tr e e :

def p o s t o r d e r ( s e l f ) : if not s e l f . i s _ e m p t y () :

for p in s e l f . _ s u b t r e e _ p o s t o r d e r ( s e l f . r o o t () ) :

y i e l d p

def _ s u b t r e e _ p o s t o r d e r ( self , p ) : for c in s e l f . c h i l d r e n ( p ) :

for o t h e r in s e l f . _ s u b t r e e _ p o s t o r d e r ( c ) : y i e l d o t h e r

y i e l d p

71

(94)

Preorder and Postorder Traversals of General Trees

Both preorder and postorder traversal algorithms are efficient ways to access all the positions of a tree.

At each positionp, the nonrecursive part of the traversal algorithm requires timeO(cp+1), wherecp is the number of children ofp, under the assumption that the “visit” itself takesO(1)time.

The overall running time for the traversal of tree T isO(n), where n is the number of positions in the tree. This running time is asymptotically optimal since the traversal must visit all thenpositions of the tree.

(95)

Preorder and Postorder Traversals of General Trees

Both preorder and postorder traversal algorithms are efficient ways to access all the positions of a tree.

At each positionp, the nonrecursive part of the traversal algorithm requires timeO(cp+1), wherecp is the number of children ofp, under the assumption that the “visit” itself takesO(1)time.

The overall running time for the traversal of tree T isO(n), where n is the number of positions in the tree. This running time is asymptotically optimal since the traversal must visit all thenpositions of the tree.

72

(96)

Preorder and Postorder Traversals of General Trees

Both preorder and postorder traversal algorithms are efficient ways to access all the positions of a tree.

At each positionp, the nonrecursive part of the traversal algorithm requires timeO(cp+1), wherecp is the number of children ofp, under the assumption that the “visit” itself takesO(1)time.

The overall running time for the traversal of tree T isO(n), where n is the number of positions in the tree. This running time is asymptotically optimal since the traversal must visit all thenpositions of the tree.

(97)

Tree Traversal Algorithms

Breadth-First Tree Traversal

(98)

Breadth-First Tree Traversal

Definition : Breadth-First Tree Traversal

Although the preorder and postorder traversals are common ways of visiting the positions of a tree, another common approach is to traverse a tree so that we visit all the positions at depthd before we visit the positions at depth d+1. Such an algorithm is known as a breadth-first traversal.

(99)

Breadth-First Tree Traversal

74

(100)

Breadth-First Tree Traversal

c l a s s Tr e e :

def b r e a d t h f i r s t ( s e l f ) : if not s e l f . i s _ e m p t y () :

f r i n g e = L i n k e d Q u e u e () f r i n g e . e n q u e u e ( s e l f . r o o t () ) w h i l e not f r i n g e . i s _ e m p t y () :

p = f r i n g e . d e q u e u e () y i e l d p

for c in s e l f . c h i l d r e n ( p ) : f r i n g e . e n q u e u e ( c )

(101)

Tree Traversal Algorithms

Inorder Traversal of a Binary Tree

(102)

Inorder Traversal of a Binary Tree

During an inorder traversal, we visit a position between the recursive traversals of its left and right subtrees. The inorder traversal of a binary tree T can be informally viewed as visiting the nodes of T “from left to right”.

Indeed, for every position p, the inorder traversal visits p after all the positions in the left subtree of p and before all the positions in the right subtree of p.

(103)

Inorder Traversal of a Binary Tree

During an inorder traversal, we visit a position between the recursive traversals of its left and right subtrees. The inorder traversal of a binary tree T can be informally viewed as visiting the nodes of T “from left to right”.

Indeed, for every position p, the inorder traversal visits p after all the positions in the left subtree of p and before all the positions in the right subtree of p.

76

(104)

Inorder Traversal of a Binary Tree

(105)

Inorder Traversal of a Binary Tree

c l a s s B i n a r y T r e e ( T r e e ) :

def i n o r d e r ( s e l f ) :

if not s e l f . i s _ e m p t y () :

for p in s e l f . _ s u b t r e e _ i n o r d e r ( s e l f . r o o t () ) :

y i e l d p

def _ s u b t r e e _ i n o r d e r ( self , p ) : if s e l f . l e f t ( p ) is not No n e :

for o t h e r in s e l f . _ s u b t r e e _ i n o r d e r ( s e l f . le f t ( p ) ) :

y i e l d o t h e r y i e l d p

if s e l f . r i g h t ( p ) is not N o n e :

for o t h e r in s e l f . _ s u b t r e e _ i n o r d e r ( s e l f . r i g h t ( p ) ) :

y i e l d o t h e r

78

(106)

Expression Tree

(107)

Expression Tree

f r o m l i n k e d _ b i n a r y _ t r e e i m p o r t L i n k e d B i n a r y T r e e

c l a s s E x p r e s s i o n T r e e ( L i n k e d B i n a r y T r e e ) :

def _ _ i n i t _ _ ( self , token , l e f t = None , r i g h t = N o n e ) :

s u p e r() . _ _ i n i t _ _ ()

if not i s i n s t a n c e( token , str) :

r a i s e T y p e E r r o r ( ’ T o k e n m u s t be a s t r i n g ’ ) s e l f . _ a d d _ r o o t ( t o k e n )

if l e f t is not N o n e :

if t o k e n not in ’ + -* x / ’ :

r a i s e V a l u e E r r o r ( ’ t o k e n m u s t be v a l i d o p e r a t o r ’ )

se l f . _ a t t a c h ( s e l f . r o o t () , left , r i g h t )

79

(108)

Expression Tree

def _ p a r e n t h e s i z e _ r e c u r ( self , p , r e s u l t ) : if s e l f . i s _ l e a f ( p ) :

r e s u l t . a p p e n d (str( p . e l e m e n t () ) ) e l s e:

r e s u l t . a p p e n d ( ’ ( ’ )

se l f . _ p a r e n t h e s i z e _ r e c u r ( s e l f . l e f t ( p ) , r e s u l t )

r e s u l t . a p p e n d ( p . e l e m e n t () )

se l f . _ p a r e n t h e s i z e _ r e c u r ( s e l f . r i g h t ( p ) , r e s u l t )

r e s u l t . a p p e n d ( ’ ) ’ )

(109)

Expression Tree

def _ _ s t r _ _ ( s e l f ) : p i e c e s = []

s e l f . _ p a r e n t h e s i z e _ r e c u r ( s e l f . r o o t () , p i e c e s )

r e t u r n ’ ’ . j o i n ( p i e c e s )

81

(110)

Expression Tree

def e v a l u a t e ( s e l f ) :

r e t u r n s e l f . _ e v a l u a t e _ r e c u r ( s e l f . r o o t () )

(111)

Expression Tree

def _ e v a l u a t e _ r e c u r ( self , p ) : if s e l f . i s _ l e a f ( p ) :

r e t u r n f l o a t( p . e l e m e n t () ) e l s e:

op = p . e l e m e n t ()

l e f t _ v a l = s e l f . _ e v a l u a t e _ r e c u r ( s e l f . l e f t ( p ) )

r i g h t _ v a l = s e l f . _ e v a l u a t e _ r e c u r ( s e l f . r i g h t ( p ) )

if op == ’ + ’ :

r e t u r n l e f t _ v a l + r i g h t _ v a l el i f op == ’ - ’ :

r e t u r n l e f t _ v a l - r i g h t _ v a l el i f op == ’ / ’ :

r e t u r n l e f t _ v a l / r i g h t _ v a l el s e:

r e t u r n l e f t _ v a l * r i g h t _ v a l 83

(112)

Expression Tree

def t o k e n i z e ( raw ) :

S Y M B O L S = set( ’ + - x * / ( ) ’ ) m a r k = 0

t o k e n s = []

n = len( raw )

for j in r a n g e( n ) : if raw [ j ] in S Y M B O L S :

if m a r k != j :

t o k e n s . a p p e n d ( raw [ m a r k : j ]) if raw [ j ] != ’ ’ :

t o k e n s . a p p e n d ( raw [ j ]) ma r k = j +1

if m a r k != n :

t o k e n s . a p p e n d ( raw [ m a r k : n ])

(113)

Expression Tree

def b u i l d _ e x p r e s s i o n _ t r e e ( t o k e n s ) : S = []

for t in t o k e n s : if t in ’ + - x */ ’ :

S . a p p e n d ( t )

e l i f t not in ’ () ’ :

S . a p p e n d ( E x p r e s s i o n T r e e ( t ) ) e l i f t == ’ ) ’ :

r i g h t = S . pop () op = S . pop () le f t = S . pop ()

S . a p p e n d ( E x p r e s s i o n T r e e ( op , left , r i g h t ) ) r e t u r n S . pop ()

85

(114)

Expression Tree

if _ _ n a m e _ _ == ’ _ _ m a i n _ _ ’ :

big = b u i l d _ e x p r e s s i o n _ t r e e ( t o k e n i z e ( ’ ( ( ( ( 3 + 1) * 3) /((9 -5) +2) ) -((3 x (7 -4) ) +6) ) ’ ) )

p r i n t( big , ’ = ’ , big . e v a l u a t e () )

Referensi

Dokumen terkait

MEDIA AND PUBLIC RELATIONS POLICY The Communications Office at the University of Liberal Arts Bangladesh ULAB exists to strategize and provide accurate, timely, and pertinent