affiliate marketing
Showing posts with label Tree Traversal. Show all posts
Showing posts with label Tree Traversal. Show all posts

Monday, 12 December 2011

Breadth First Traversal



These three are certainly not the only possible traversal orders. Another very natural traversal order is ``level by level'' - the root is processed first, all its children are processed next, then all of their children, etc. down to the bottom level. This is called breadth first traversal. In the above example, it would process nodes in the order: A-B-C-D-E-F. It is not difficult to write a breadth-first traversal, but is not quite as simple as the traversal orders just described.

2. Tree Traversal


What I've just called ``scanning through'' a tree is actually called traversing a tree.
General Definition: to traverse a data structure is to process, however you like, every node in the data structure exactly once.
Note: You may ``pass through'' a node as many times as you like but you must only process the node once.
E.g. we can talk about ``traversing a list'', which means going through the list and processing every node once. We had a special name for this: map.
For a specific data structure, we talk about the different orders in which it might be traversed. For a list there are two common traversal orders: first-to-last (the most common) and last-to-first.
The general recursive pattern for traversing a (non-empty) binary tree is this: At node N you must do these three things: