Using trees is a way to create a data structure that mimics a "yes/no" decision making process. resource
"Trees can have any number of children per node, but Binary Trees restrict the number of children to two (hence our left and right children)."
K: The number that specifies the maximum number of children any node may have in a k-ary tree. K=2 for a binary tree
Depth First Prioritizes going through the height of the tree first. The most common way to traverse through a tree is to use recursion.
- Pre-order root > left > right
- In-order left > root > right
- Post-order left > right >root
- Pre-order Pre-order
Pre-order :
- Root, A, is the output value
- We will then look to the left, B
- Look to the left of that last node which is a leaf, D. D would then get popped off
- We look at the next leaf, E
- Pop off B
- Back to the root of A
- Look at C
- Look to the F
- Pop off F
- Pop off C
- Back to the root of A
Breadth First Iterates through the tree going through each level of the tree node by node. Traversal uses a queue.
- Root, A, is in the queue and needs to be dequeued.
- Enqueue left, B, and right, C, child.
- You then dequeue the front nodes (B then C).
- Continue the enqueue and dequeue process on with the leafs