What is a tree?
- Algorithms course
- Intermediate
- Lesson 25/80
- 4 min
A hierarchical structure of root and child nodes.
What is a tree?
A tree is a hierarchical, acyclic data structure of nodes and edges. There is a root node; each node can have zero or more children.
Nodes close to the root are internal; nodes with no children are leaves. Trees are ideal for representing hierarchical data (file systems, org structures).
A binary tree is a special tree where each node has at most two children.
Node and edge
Each node holds a value and child pointers. In a binary tree there are left and right pointers. An edge is a parent-child link.
A tree with n nodes has n-1 edges (every node except the root has one parent). The height is the number of edges on the longest root-to-leaf path.
In Python a node is usually represented with a class.
Practice Create a node
Write a Node class with val, left, right fields. Print 5 with print(Node(5).val).
Starter code
class Node:
def __init__(self, val):
# Init nodeSample solution
class Node:
def __init__(self, val):
# Init node
self.val = val
self.left = None
self.right = None
print(Node(5).val)Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a leaf node?
- The root node
- A node with no children Correct answer
- One with two children
- The topmost
Explanation: A node with no children
2 Node class
class Node:
def __init__(self, val):
self.val = val
self.left = ____
self.right = None
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
Explanation: None is right.
3 What is a tree: match the terms
| Term | Meaning |
|---|---|
Root |
Topmost |
Leaf |
No children |
Internal |
Has children |
Edge |
Link |