11
Presented by: Mubashar Mehmood Implementation of Trees

Implementation of trees

Embed Size (px)

DESCRIPTION

basic information about Tree, how to implement them into algorithms.

Citation preview

Page 1: Implementation of trees

Presented by:Mubashar Mehmood

Implementation of Trees

Page 2: Implementation of trees

A tree is a nonlinear data structure that models a hierarchical organization.

A tree consists of nodes with a parent-child relation.

Every node except one has a unique parent. There is a unique path from root node to

each child node.

Tree

A

B

D E

C

Page 3: Implementation of trees

List Tree

Start head root# before 1 (prev) 1 (parent)# after 1 (next) >= 1 (children)

Comparison of Tree and List

Page 4: Implementation of trees

Binary tree associated with an arithmetic expression internal nodes: operators external nodes: operands

Example: arithmetic expression tree for the expression (2 (a - 1) + (3 b))

Arithmetic Expression Tree

+

-2

a 1

3 b

Page 5: Implementation of trees

Binary tree associated with a decision process internal nodes: questions with yes/no answer external nodes: decisions

Example: dining decision

Decision Tree

Want a fast meal

How about coffee On expense account

Starbucks Wendy’s Gotham Apple

Yes No

Yes No Yes No

Page 6: Implementation of trees

A special class of trees: max degree for each node is 2.

Recursive definition: A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree.

Binary Trees

B

E

H I

Page 7: Implementation of trees

Sequential Representation

Binary Tree Representations

A

B

E

C

D

AB--C------D--.E

[1][2][3][4][5][6][7][8][9].[16]

(1) waste space(2) insertion/deletion problem

ABCDEFGHI

[1][2][3][4][5][6][7][8][9]

A

B C

GE

I

D

H

F

Page 8: Implementation of trees

Linked Representation

Binary Tree Representations

dataleft right

left right

data

Page 9: Implementation of trees

• Let L, V, and R stand for moving left, visiting the node, and moving right.

• There are six possible combinations of traversal• lRr, lrR, Rlr, Rrl, rRl, rlR

• Adopt convention that we traverse left before right, only 3 traversals remain• lRr, lrR, Rlr• inorder, postorder, preorder

Binary Tree Traversals

Page 10: Implementation of trees

Binary Tree Traversals

+

*

A

*

/

E

D

C

B

inorder traversalA / B * C * D + Einfix expressionpreorder traversal+ * * / A B C D Eprefix expressionpostorder traversalA B / C * D * E +postfix expression

Page 11: Implementation of trees

Inorder Traversal

3

1

2

5

7 9

8

4

6

Algorithm inOrder(v)if hasLeft (v)

inOrder (left (v))visit(v)if hasRight (v)

inOrder (right (v))