UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

Tree Traversals

Traversing a tree means to visit each of the nodes and to print out the values stored in each node as it is visited. There are three standard ways to traverse a binary tree :

All of the traversals are recursive in nature. In the preorder, the value found at the node is printed first, then movement through the tree continues. Here's the function called PreOrder:

void PreOrder (nodePtr curr) { if (curr != NULL) { printf ("%4d", curr -> data); PreOrder (curr -> leftChild); PreOrder (curr -> rightChild); } }

In the postorder, movement to the left is done, then movement to the right, and then the value of node is printed. (The value contained in a node will only be printed after all of its children and grandchildren, etc have been printed. Here's the function called PostOrder:

void PostOrder (nodePtr curr) { if (curr != NULL) { PostOrder (curr -> leftChild); PostOrder (curr -> rightChild); printf ("%4d", curr -> data); } }

In order, as expected, will print the values contained in all of the nodes of the tree in order. Here's the function called InOrder:

void InOrder (nodePtr curr) { if (curr != NULL) { InOrder (curr -> leftChild); printf ("%4d", curr -> data); InOrder (curr -> rightChild); } }

Example traversals will be shown in class



CSEE | 201 | 201 F'98 | lectures | news | help

Wednesday, 09-Dec-1998 09:07:57 EST