Introduction
Imagine you have a family tree or an organizational chart. You want to know how far someone is from the top or how tall the whole tree is. Height and depth help us measure these distances in tree structures.
Think of a family tree where the oldest ancestor is at the top. The depth of a person is how many generations they are away from that ancestor. The height of a person is how many generations are below them until the youngest descendant.
┌───── Root (depth=0, height=3) ─────┐ │ │ ┌───┴───┐ ┌───┴───┐ │ │ │ │ Node1 Node2(depth=1, height=1) Node3 Node4 (depth=1, height=2) (depth=1, height=0) │ Leaf1 (depth=2, height=0)
class Node: def __init__(self, value): self.value = value self.children = [] def compute_depth(node, root, depth=0): if node == root: return depth for child in root.children: d = compute_depth(node, child, depth + 1) if d != -1: return d return -1 def compute_height(node): if not node.children: return 0 return 1 + max(compute_height(child) for child in node.children) # Build a sample tree root = Node('root') child1 = Node('child1') child2 = Node('child2') leaf = Node('leaf') root.children = [child1, child2] child1.children = [leaf] # Compute depth and height print('Depth of leaf:', compute_depth(leaf, root)) print('Height of root:', compute_height(root))