Key Takeaways: A Tree is a non-linear, hierarchical data structure. Unlike Arrays or Linked Lists which organize data in a straight line, Trees organize data like branches on a family tree or folders on a computer.
So far, every data structure we have learned (Arrays, Linked Lists, Stacks, Queues) has been Linear. Data goes in a straight, sequential line from start to finish.
However, many real-world problems are not linear. They are Hierarchical. To solve these problems, Computer Scientists invented the Tree data structure!
A Tree is a collection of entities called Nodes.
Nodes are connected by edges (links). Each node contains a value or data, and it may or may not have a child node.
C: drive (Root). Inside it are folders like Users and Windows. Inside Users are more folders like Documents and Downloads.<html> tag is the root. Inside are <head> and <body> tags, which contain more tags!Before we can write code for Trees, you absolutely must know the terminology. It comes up in every technical interview!
Tree Terminology: Notice how it looks like a real tree turned upside down!
Here is your cheat sheet:
If Arrays and Hash Maps are so fast, why do we need Trees?
O(n) time. But if you organize your data into a special type of tree (like a Binary Search Tree), you can search it in O(log n) time. It is much faster!Let's write a simple Python script to create a Tree Node.
Unlike a Linked List node which only has one next pointer, a Tree node can have a list of children pointers!
# 1. Create the TreeNode Class class TreeNode: def __init__(self, data): self.data = data # A node can have multiple children! self.children = [] def add_child(self, child_node): self.children.append(child_node) # 2. Build the Tree (Like an Org Chart) root = TreeNode("CEO") vp_sales = TreeNode("VP of Sales") vp_tech = TreeNode("VP of Tech") manager1 = TreeNode("Sales Manager") engineer1 = TreeNode("Lead Engineer") # 3. Connect the Nodes root.add_child(vp_sales) root.add_child(vp_tech) vp_sales.add_child(manager1) vp_tech.add_child(engineer1) # 4. Test it out! print("Root:", root.data) print("CEO's Children:") for child in root.children: print("-", child.data)
In Tree terminology, what is a "Leaf"?