reading-notes

Code Fellows courses Notes

This project is maintained by QamarAlkhatib

Tree

Common Terminology

Example:

tree


Traversals

Traversing a tree allows us to search for a node, print out the contents of a tree, and much more.

Types of traversals:

Depth-first traversal

Depth first traversal is where we prioritize going through the depth (height) of the tree first. There are multiple ways to carry out depth first traversal, and each method changes the order in which we search/print the root. Here are three methods for depth first traversal:

Here is a simple example: example


Algorithm pseudocode:

ALGORITHM preOrder(root)

  OUTPUT <-- root.value

  if root.left is not NULL
      preOrder(root.left)

  if root.right is not NULL
      preOrder(root.right)


ALGORITHM inOrder(root)
# INPUT <-- root node
# OUTPUT <-- in-order output of tree node's values

    if root.left is not NULL
        inOrder(root.left)

    OUTPUT <-- root.value

    if root.right is not NULL
        inOrder(root.right)
ALGORITHM postOrder(root)
#// INPUT <-- root node
#// OUTPUT <-- post-order output of tree node's values

    if root.left is not NULL
        postOrder(root.left)

    if root.right is not NULL
        postOrder(root.right)

    OUTPUT <-- root.value