A Tree is a non-linear hierarchical data structure made up of nodes connected by edges.
It starts with a special node called the root, and each node can have child nodes, forming a branching structure — like an upside-down tree.
It’s called a “tree” because it visually resembles an upside-down tree, with a single root node at the top and branches that spread downwards to other nodes, called children.

Key Concepts

  • Root: The topmost node (A tree has only one root node)
  • Parent: A node that has child nodes
  • Child: A node that descends from another node (parent)
  • Leaf: A node that has no children
  • Edge: The connection between nodes
Tree2 Pn

Use Cases

Trees are incredibly useful for organizing and managing hierarchical data efficiently.
  1. File Systems: The directory structure on your computer (folders and files) is a classic example of a tree. The root directory is the top-level node, and subdirectories and files are its children.
  2. Databases: B-trees and B+ trees are specialized tree structures used in database systems to index data, allowing for fast searches, insertions, and deletions.
  3. Syntax Parsing: Compilers use syntax trees to represent the structure of programming code, which helps in identifying errors and translating the code into machine-readable instructions.
  4. **Family Trees: **Ancestors and descendants in genealogy.
class TreeNode:
    def __init__(self, data):
        self.data = data
        self.children = []  # A list to hold the children nodes

    def add_child(self, child_node):
        self.children.append(child_node)

# Create the root node
root = TreeNode("Drinks")

# Create child nodes for the root
hot = TreeNode("Hot")
cold = TreeNode("Cold")

# Add the child nodes to the root
root.add_child(hot)
root.add_child(cold)

# Create grandchildren nodes
tea = TreeNode("Tea")
coffee = TreeNode("Coffee")
juice = TreeNode("Juice")
soda = TreeNode("Soda")

# Add the grandchildren to their respective parents
hot.add_child(tea)
hot.add_child(coffee)
cold.add_child(juice)
cold.add_child(soda)

# A simple function to traverse and print the tree structure
def print_tree(node, level=0):
    print("  " * level + "- " + node.data)
    for child in node.children:
        print_tree(child, level + 1)

print_tree(root)
https://en.wikipedia.org/wiki/Tree_(abstract_data_type)