A TREE is a hierarchical, non-linear structure where data is
organized in a parent-child
relationship between nodes. It consists of nodes connected by edges, with a root node at the top and
branches extending down to child nodes.
Easy Definition (Real-life Understanding):
A TREE is a way to show things that have a hierarchical
structure — like a family TREE, or the
folders inside a computer. Imagine an upside-down TREE 🌲 with
one top point (called the root) and many branches growing
downward. Each point (called a node) can have children (further branches), or none at all (these are
leaves).
TREE in Data Structures (Technical
Explanation):
A TREE in data structures is a non-linear data structure that
is used to represent hierarchical
relationships. It consists of nodes connected by edges. The topmost node is called the root. Each
node can have zero or more child nodes.
A node with no children is called a leaf node. Every node (except the root) has exactly one parent.
Key Terms:
Root – The first/top node.
Parent – A node that has children.
Child – A node under a parent.
Leaf – A node with no children.
Edge – A connection between two nodes.
Subtree – A part of a TREE that is itself a tree.
Binary TREE – Each node has at most 2 children.
Binary Search TREE (BST) – A binary TREE where left < parent < right.
AVL TREE – A balanced BST.
Heap – A complete binary TREE with max/min at the root.
Trie – A TREE used for storing strings.
Imagine how your files are stored on your computer:
Root Folder = Main Drive (like C:/)
Inside it are Folders (like Documents, Pictures)
Inside Documents there may be more folders like Assignments, Projects
Inside those folders are files like project.docx, notes.txt
This creates a tree-like hierarchy.
To insert a new node, we start from the root and find the correct position by comparing values (in BSTs) or adding as the next available child (in general TREE or heaps).
TIME COMPLEXITY - O(log n) in BST (balanced), O(n) in worst case
Removing a node involves three cases: node with no child (leaf), one child, or two children. In BSTs, we may need to replace it with in-order successor or predecessor.
TIME COMPLEXITY - O(log n) average, O(n) worst case
Searching means finding whether a value exists in the TREE. We start from the root and follow the structure (e.g. left or right based on value for BST).
TIME COMPLEXITY - O(log n) average, O(n) worst case
Traversal means visiting all nodes in a specific order:
TIME COMPLEXITY - O(n) for all traversals
It calculates the height (longest path from root to a leaf) or depth (distance from root to a node) of the tree.
TIME COMPLEXITY - O(n)
In a Binary Search Tree, minimum is the leftmost node, and maximum is the rightmost node.
TIME COMPLEXITY - O(log n) average, O(n) worst case