It is a collection of nodes that are connected by edges and has a hierarchical relationship between the nodes.
Depth First: prioritize going through the depth (height) of the tree first. Three methods:
Breadth First: traversal iterates through the tree by going through each level of the tree node-by-node.
pre-order traversal:
Pre-order means that the root has to be looked at first.
ALGORITHM preOrder(root)
OUTPUT <– root.value
if root.left is not NULL preOrder(root.left)
if root.right is not NULL preOrder(root.right)
In-order:
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)
The biggest difference between each of the traversals is when you are looking at the root node.
ALGORITHM breadthFirst(root)
// INPUT <-- root node
// OUTPUT <-- front node of queue to console
Queue breadth <-- new Queue()
breadth.enqueue(root)
while breadth.peek()
node front = breadth.dequeue()
OUTPUT <-- front.value
if front.left is not NULL
breadth.enqueue(front.left)
if front.right is not NULL
breadth.enqueue(front.right)