Loading...

PPT – EE441 Data Structures Chapter IX Recursion, Trees PowerPoint presentation | free to view - id: abe25-YzkwN

The Adobe Flash plugin is needed to view this content

EE441 Data StructuresChapter IXRecursion, Trees

- Özgür B. Akan
- Department of Electrical Electronics

Engineering - Middle East Technical University
- akan_at_eee.metu.edu.tr
- www.eee.metu.edu.tr/akan

Recursive Functions

- Some calculations have recursive character
- For example, N!N(N-1)!
- To be able to implement such algorithms, we write

functions that call themselves, i.e., recursive

functions - Recursion
- Method/Function calls itself
- Each call is closer to Base Case
- Base Case Termination Condition
- Each call Loop iteration
- Each call subject to stacking

Recursion-based Processing

- ... doIt(..............)
- if (there is data) // EOF processing
- do something
- ...
- doIt(..........)

The recursive call... doIt( ) calls itself...

Recursion-based Processing

- ... doIt(... int count ...)
- if(count lt terminalValue)
- do something
- ...
- doIt(... count 1 ...)

The recursive call... doIt( ) calls itself...

The value of count approaches the terminalValue

each call

Filling an Array - Recursion

- // int howmany is global and initialized to 0
- ... void getinput(... array ) ...
- int num
- fin gtgt num
- if (!fin.eof( )...)
- arrayhowmany num
- howmany
- getinput(array)

Finding the Sum - Recursion

- // sum is declared globally
- ... void findSum(int array , int x, int

howmany)... - if(x lt howmany)
- sum arrayx
- findSum(array, x1, howmany)

The value of x approaches howmany each call

Trees

- A tree is a set of nodes which is either null or

with one node designated as the root and the

remaining nodes partitioned into smaller trees,

called sub-trees. - e.g.,
- T1 (NULL Tree)
- T2a a is the root, the rest is T1
- T3a, b,c,d,e,f,g,h,i

Trees

- Graphical representation of
- T1 (NULL Tree)
- T2a a is the root, the rest is T1
- T3a, b,c,d,e,f,g,h,i

Trees

- The level of a node is the length of the path

from the root to that node - The depth of a tree is the maximum level of any

node in the tree - The degree of a node is the number of partitions

in the subtree which has that node as the root - Nodes with degree0 are called leaves

Binary Trees

- A tree in which the maximum degree of any node is

2. - A binary tree may contain up to 2n nodes at level

n. - A complete binary tree of depth N has 2k nodes at

levels k0,,N-1, and all leaf nodes at level N

occupy leftmost positions. - If level N has 2N nodes as well, then the

complete binary tree is a full tree. - If all nodes have degree1, the tree is a

degenerate tree (or simply linked list)

level 0

level 1

level 2

level 3

level 4

Binary Trees - Examples

- A degenerate tree of depth 5 has 6 nodes
- A full tree of depth 3 has
- 124815 nodes
- A full tree of depth N has
- 2N1-1 nodes
- A complete tree of depth N has
- 2N-1ltm 2N1-1 nodes or
- 2Nm 2N1-1 nodes.
- Exercise What is the depth of a complete tree

with m nodes?

Show these as exercise

Data Structures and Representations of Trees

Left data right

T

?

?

?

?

?

- template ltclass Tgt
- class TreeNode
- private
- TreeNodeltTgt left
- TreeNodeltTgt right
- public
- T data
- //constructor
- TreeNode(const T item, TreeNodeltTgt

lptrNULL, TreeNodeltTgt rptrNULL) - //access methods for the pointer fields
- TreeNodeltTgt Left(void) const
- TreeNodeltTgt Right(void) const

Data Structures and Representations of Trees

- template ltclass Tgt //constructor
- TreeNodeltTgt TreeNode(const T item, TreeNodeltTgt

lptr, - TreeNodeltTgt rptr) data(item), left(lptr),

right(rptr) - // a function dynamically allocate memory for a

new object - template ltclass Tgt
- TreenodeltTgt GetTreeNode(T item, TreeNodeltTgt

lptrNULL, TreeNodeltTgt rptrNULL) - TreeNodeltTgt p
- pnew TreeNodeltTgt (item, lptr, rptr)
- if (pNULL) // if "new" was unsuccessful
- cerrltltMemory allocation failure"ltltendl
- exit(1)
- return p
- // a function to deallocate memory template

ltclass Tgt - void FreeTreeNode(TreeNode ltTgt p)

Data Structures and Representations of Trees

- Example
- TreeNodeltchargt t
- tGetTreeNode('a', GetTreeNode('b',NULL,

GetTreeNode('c')), - GetTreeNode('d', GetTreeNode('e')))

Result

Tree Traversal Algorithms

- DEPTH-FIRST traversal algorithms
- Inorder
- Traverse left subtree
- Visit node (i.e. process node)
- Traverse right subtree
- Preorder
- Visit node
- Traverse Left
- Traverse right
- Post-order
- Traverse left
- Traverse right
- Visit node

Tree Traversal Algorithms

- e.g. An arithmetic expression tree stores

operands in leaves, operators in non-leaf nodes

Inorder traversal (LNR) (A-B)((C/D)(E-F)) A-BC

/DE-F (parentheses assumed) Preorder traversal

(NLR) -AB/CD-EF Postorder traversal

(LRN) AB-CD/EF-

If operand PUSH

Note Postorder traversal, with the following

implementation of visit

If operator POP two operands calculate

PUSH result back

Verify as an exercise!

corresponds to arithmetic expression evaluation!

Tree Traversal Algorithms

- e.g. Counting leaves in a tree

template ltclass Tgt void CountLeaf(TreeNodeltTgt t,

int count) if (t !NULL) // using

postorder traversal CountLeaf(t-gtLeft(),count)

CountLeaf(t-gtRight(),count) // visiting a

node means incrementing if leaf if

(t-gtLeft()NULL t-gtRight()NULL) count

Tree Traversal Algorithms

- e.g. Computing depth of a tree

template ltclass Tgt int Depth(TreeNodeltTgt t)

int depthLeft, depthRight, depthval if

(tNULL) depthval-1 // if empty, depth-1

else depthLeftDepth(t-gtleft()) depthRig

htDepth(t-gtRight()) depthval1(depthLeftgtdepth

Right ? depthLeftdepthRight)) return

depthval

Conditional expression syntax CONDITION?T-EXPF-E

XP

if true T-EXP, else F-EXP returned!

Breadth-First Traversal

- The preorder, postorder, and inorder traversals

are depth-first. - A Breadth-first traversal algorithm
- e.g. Level-traverse traversal sequence a,

b, c, d, e, f

- Algorithm Level-Traverse
- Insert root node in queue
- While queue is not empty
- Remove front node from queue and visit it
- Insert Left child
- Insert right child

Breadth-First Traversal

- template ltclass tgt
- void LevelScan(TreeNodeltTgt t)
- QueueltTreeNodeltTgtgt Q // queue of pointers
- TreeNodeltTgt p
- // insert root
- Q.Qinsert(t)
- while(!Q.Empty())
- pQ.Qdelete()
- visit(p-gtdata)
- if (p-gtLeft()!NULL) Q.Qinsert(p-gtLeft())
- if (p-gtRight()!NULL) Q.Qinsert(p-gtRight())

Binary Search Trees

- A BST is a BT in which data values in the left

subtree of every node are less than the data

value in the node and those in the right subtree

are greater. - e.g.
- Rather than using the full data field, a key

field whose value must be unique in every node,

is used for constructing the BST. - NOTE In a BST, searching and inserting are

simple, but deleting may be problematic. -what

to do when a root is deleted?

NOTE Inorder traversal generates ascending

sequence

Multiway Search Trees

- Definition An m_way search tree is a tree in

which all nodes are of degreeltm. (It may be

empty). - A non empty m_way search tree has the following

properties - a) It has nodes of type

- b) key1 lt key2 lt...lt key(m-1) in other words,
- key ilt key(i1), 1ltiltm-1
- c) All Key values in subtree Ti are greater than

Key i-1 and less than Key i1 - Sometimes, we have an additional entry at the

leftmost field of every node, indicating the

number of nonempty key values in that node.

Multiway Search Trees

- e.g. 3_way search tree
- Nodes will be of type

Balanced Trees (B_Trees)

- A B_tree of order m is an m_way search tree

(possibly empty) satisfying the following

properties (if it is not empty) - a) All nodes other than the root node and leaf

nodes have at least m/2 children, - b) The tree is balanced. (If we modify all link

fields of leaf nodes to point to special nodes

called failure nodes, these are at the same

level) - e.g. B-Tree of order 3

Inserting Key to B-Trees

- Insert a new key value x, into a B-tree
- Always insert at the leaf nodes.
- The resulting tree must also be a B-tree. (It

must be balanced.) - If space is not available at the node into which

insertion will be made - Create a hypothetical node of order n1
- Split into two nodes, insert extracted center key

into parent - Repeatedly apply this until no further splits

necessary

Inserting Key to B-Trees

- Example
- 1) Insert 38 to the B-tree of the above example
- First of all, we do a search for 38 in the given

B-tree. - We hit the failure node marked with "" . The

parent of that failure node has only one key

value so it has space for another one. - Insert 38 there , add a new failure node, which

is marked as "" in the following figure, and

return.

Inserting Key to B-Trees

- 2) Now, insert 55 to this B-tree.
- We do the search and hit the failure node "".

However, it's parent node does not have any space

for a key value. Now, assume we create a new node

instead of

So, we end up

/

Inserting Key to B-Trees

- 3) Now, let us insert 37 to this B_tree
- We search for 37, and hit a failure node between

35 and 38. So, we have to create

Inserting Key to B-Trees

- So, we end up with

40

If we can not insert to the root node, we split

and create a new root node. For example try to

insert 34, 32, and 33. Thus, the height of the

B-tree increases by 1 in such a case. Deletion

algorithm is much more complicated! It will not

be considered here.