A tree is a non-linear, hierarchical data structure that consists of nodes connected by edges.
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.
Trees are incredibly useful for organizing and managing hierarchical data efficiently.
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.
Databases: B-trees and B+ trees are specialized tree structures used in database systems to index data, allowing for fast searches, insertions, and deletions.
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.
**Family Trees: **Ancestors and descendants in genealogy.
Copy
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 noderoot = TreeNode("Drinks")# Create child nodes for the roothot = TreeNode("Hot")cold = TreeNode("Cold")# Add the child nodes to the rootroot.add_child(hot)root.add_child(cold)# Create grandchildren nodestea = TreeNode("Tea")coffee = TreeNode("Coffee")juice = TreeNode("Juice")soda = TreeNode("Soda")# Add the grandchildren to their respective parentshot.add_child(tea)hot.add_child(coffee)cold.add_child(juice)cold.add_child(soda)# A simple function to traverse and print the tree structuredef print_tree(node, level=0): print(" " * level + "- " + node.data) for child in node.children: print_tree(child, level + 1)print_tree(root)