Lesson 15/25 ยท ๐ณ Trees
๐ณ TreesLesson 15/25
Phase 5 ยท Trees22 min
Binary Trees
Hierarchical data, the structure behind file systems, compilers, and search
A binary tree is a hierarchical structure where each node has at most 2 children (left and right). Trees are the natural data structure for hierarchical data: file systems, HTML DOM, organization charts, expression evaluation.
Key terms:Root, top node (no parent) Leaf, node with no children Height, longest path from root to leaf Depth, distance from root to a node
Key terms:
Tree node and basic operationspython
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# Build a tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1,
TreeNode(2, TreeNode(4), TreeNode(5)),
TreeNode(3)
)
def height(node):
if not node: return 0
return 1 + max(height(node.left), height(node.right))
def count_nodes(node):
if not node: return 0
return 1 + count_nodes(node.left) + count_nodes(node.right)
print(height(root)) # โ 3
print(count_nodes(root)) # โ 5๐คQuick Check
A "balanced" binary tree has height O(log n) where n is the number of nodes. Why does this matter?
Practice Exercises
0/1 solvedExercise 1 of 1easy
โฑ 00:00Maximum Depth
Find the maximum depth (height) of a binary tree.
Expected output:
Expected output:
3solution.py
1 / 1
Solve all 1 exercise to unlock completion