Lect 22 Zaheer Abbas

Preview:

Citation preview

Created by Zaheer Abbas Aghani 2k9-152

Non-Linear Data StructureTree

As list, Stack, & Queue, binary tree can also be implement in two ways.

Linked Representation Array Representation.

LINKED REPRESENTATION OF BINARY TREE: if we implement tree data in linked list then every node of linked list has three member/parts. First member is for data, second and third member for left & right child . Second & third members are structure pointers which point to the same structure as for tree node.

3Prepared by: Shumaila Bashir

Sheikh(Lecturer, ITC)

Tree Structure: Linked Representation of tree:

A

B C

D E F

A

B C

D E F

4Prepared by: Shumaila Bashir

Sheikh(Lecturer, ITC)

Tree Structure: Array Representation of tree:- If we implement tree data in array then we need a 2 dimension array to store that data in memory & a pointer variable that store the address of root node..

A

B C

D E F

Data LN

RN

Root 3 1

2

3

4

5

6

A

B

D

C

F

E

5 2

1

4 6

null null

null

null null

null null5

Prepared by: Shumaila Bashir Sheikh(Lecturer, ITC)

Four Basic Operations

•Traversing•Searching•Inserting•Deleting

In tree creation we take three parameters node, left child & right child, so traversing of binary tree means traversing of node, left subtree and right subtree.

There are three standard ways to traversing a binary tree. These three algorithms are

1) Preorder Traversal2) Inorder Traversal3) Postorder Traversal

1.Visit the root.2.Traverse the left subtree of root in

preorder.3.Traverse the right subtree of root in

preorder.

If root is denoted as N, left subtree as L & right subtree as R then Preorder traversal is also called NLR Traversal.

Preorder Traversal: ABDECFG

A

BC

D E F G

The nodes are visited in preorder as: ABDHECFIG

A

BC

D E F G

H I

1. Traverse the left subtree of root in Inorder.

2. Visit the root.3. Traverse the right subtree of root in

Inorder.

Inorder traversal is also called LNR Traversal.

Inorder Traversal: DBEAFCG

A

BC

D E F G

The nodes are visited in inorder as: DHBEAFCG

A

BC

D E F G

H

1. Traverse the left subtree in postorder.2. Traverse the right subtree in postorder.3. Visit the Root.

Postorder traversal is also called LRN Traversal.

Postorder Traversal: DEBFGCA

A

BC

D E F G

The nodes are visited in postorder as: HDEBFGCA

A

BC

D E F G

H

In level order traversal, we traverse the nodes according to their levels. We start traversing with the level 0, then level traverse all the nodes of level 1, & then traverse all the nodes of level 2 & so on.

We traverse the nodes of a particular level from left to right.

A

EB

LEVEL 0

LEVEL 1

LEVEL 2

C K G

The nodes are traversing in level-order as: ABECKG

Recommended