What is a Tree?
A tree is a hierarchical data structure composed of nodes and edges. The primary
purpose of a tree is to represent relationships and hierarchical structures like file
systems, organizational charts or parsing expressions.
Key characteristics of Trees:
• Nodes: A tree consists of nodes (the data points or vertices)
• Edges: The connection between the nodes (often visualized as lines between
them)
• Root: The topmost node for which all other nodes are connected.
• Leaf: A node that has no children (its at the bottom of the tree)
• Parent: A node that has children.
• Child: A node that is a descendant of another node.
Note: Some types of trees, like binary search trees allow for fast searching, insertion
and deletion.
Depth: The depth of a node is the number of edges from the root to that node. (When
you want depth, count above the node)
Height: The height of a node is the longest path from that node to a leaf node. (When
you want height, count below the node. Always aim for longer)
Types of Trees:
• Basic Trees
o Binary Tree: A Binary tree is a tree where each node can have at most 2
children.
o Binary Search Tree:
▪ All the nodes in the left sub tree of a node should have values less
than the node’s value.
▪ All the nodes in the right sub tree of a node should have values
greater than the node's value.
This Property allows for efficient searching and insertion. Searching for a
value can be done in O (log n) time.
Basic Implementation in Python: