traversals | data structures

10

Click here to load reader

Upload: omair-imtiaz

Post on 06-Jul-2015

98 views

Category:

Technology


0 download

DESCRIPTION

Its a Topic of DataStructure which covers the Transversal

TRANSCRIPT

Page 1: Traversals | Data Structures

The process of systematically visiting all the nodes in a tree and performing some computation at each node in the tree is called a tree traversal.

Page 2: Traversals | Data Structures

H

D

B

A C E G I K M O

N

L

JF

OGENFBH

Page 3: Traversals | Data Structures

CODEfor each Node:Name

public void displayTree(Node n){

if( n == null ) return;

printf(n.data);

displayTree(n.left);

displayTree(n.right);

}

•Visit the node

•Visit the left subtree, if any.

•Visit the right subtree, if any.

Preorder

(N-L-R)

public void displayTree(Node n){

if( n == null ) return;

displayTree(n.left);

printf(n.data);

displayTree(n.right);

}

•Visit the left subtree, if any.

Visit the node

•Visit the right subtree, if any.

Inorder

(L-N-R)

public void displayTree(Node n){

if( n == null ) return;

displayTree(n.left);

displayTree(n.right);

printf(n.data);

}

•Visit the left subtree, if any.

•Visit the right subtree, if any.

•Visit the node

Postorder

(L-R-N)

Page 4: Traversals | Data Structures

H

D

B

A C E G I K M O

N

L

JF

ONKIJLECADH

N-L-R

Page 5: Traversals | Data Structures

H

D

B

A C E G I K M O

N

L

JF

L-N-R

ONMLKJIHGFEDCBA

Note: An inorder traversal of a BST visits the keys sorted in

increasing order.

Page 6: Traversals | Data Structures

H

D

B

A C E G I K M O

N

L

JF

L-R-N

HLNOMJKIDFGEBCA

Page 7: Traversals | Data Structures

The children of any node in a binary tree are ordered into a left child and a right child

A node can have a left anda right child, a left childonly, a right child only,or no children

The tree made up of a leftchild (of a node x) and all itsdescendents is called the left subtree of x

Right subtrees are defined similarly

7

10

1

3

11

98

4 6

5

7

12

Page 8: Traversals | Data Structures

Assume: visiting a nodeis printing its label

Preorder: 1 3 5 4 6 7 8 9 10 11 12

Inorder:4 5 6 3 1 8 7 9 11 10 12

Postorder:4 6 5 3 8 11 12 10 9 7 1

8

1

3

11

98

4 6

5

7

12

10

Page 9: Traversals | Data Structures

Assume: visiting a nodeis printing its data

Preorder: 15 8 2 6 3 711 10 12 14 20 27 22 30

Inorder: 2 3 6 7 8 10 1112 14 15 20 22 27 30

Postorder: 3 7 6 2 10 1412 11 8 22 30 27 20 15

9

6

15

8

2

3 7

11

10

14

12

20

27

22 30

Page 10: Traversals | Data Structures

Observe the output of the inorder traversal of the BST example two slides earlier

It is sorted

This is no coincidence

As a general rule, if you output the keys (data) of the nodes of a BST using inorder traversal, the data comes out sorted in increasing order

10