Data Structures: Trees
A tree is a hierarchical data structure with nodes connected by edges, starting from a single root. Each node can have children, and nodes without children are leaves. Trees are used in file systems, databases, and decision-making algorithms.
Theory
A Tree is a data structure. Just like in nature they have roots, branches and leaves. The following key terms are associated with tree structures
- Root Node - The node at the very top of the structure
- Children - subsequent nodes below the current node. Children of the root node are subsequently parent nodes of the nodes that follow.
- Braches - The lines that join the nodes are called branches.
- Leaf Nodes - Nodes without sub-trees are called leaf /terminal nodes
Binary Trees
A specific type of tree where each node is only allowed up to two children. In this case, each node contains:- A Left Pointer
- Data
- A right pointer
Tree Traversals
A tree traversal is the path you take to visit each node in the tree. The following travsersals are depth first traversals. Depth traversals are implemented using a stack:- Pre Order
- In Order
- Depth Order
Alternatively a breadth first traversal can be used. This checks the tree a level at a time. It is implmented using a queue
Interactive Tree
Enter a value to add to a tree, repeat to add more elements or click random to create a random numeric tree
Click to perform traversal
Check your understanding
Download a worksheet to test your understanding and strengthen your skills!
Browse Worksheets