From charlesreid1

Revision as of 19:25, 11 June 2017 by Admin (talk | contribs) (Created page with "Preorder traversal is a depth-first recursive tree traversal algorithm that can be defined and applied recursively. As with any recursive method, this must be split into a b...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Preorder traversal is a depth-first recursive tree traversal algorithm that can be defined and applied recursively.

As with any recursive method, this must be split into a base case and a recursive case. The base case is, we've reached an external node - no children. The recursive case is, we call preorder on each child. In this case we don't need an explicit base case and recursive case.

Here is an example of a preorder traversal pseudocode:

define public function preorder( tree )
    preorder_subtree( tree, root, 0 )

define private function preorder_subtree( tree, position, depth)
    perform visit action on position
    for child in position.children():
        preorder_subtree(tree, child, depth+1)

Because this is an intransitive recursive function - nothing is returned - the base case can remain implicit (if position is an external node, position.children is empty, and the for loop is not run, and an instance of the void recursive method returns).