Chapter 1Trees and their size
Concept
A tree is a shape, and its size counts nodes
A tree is either empty or a node with two subtrees. Its size is the number of nodes, so the empty tree has size .
The Lean definitions
/-- A binary tree shape: a leaf, or a node with a left and a right subtree. Keys are not stored. -/inductive Tree where | nil : Tree | node (left right : Tree) : Tree/-- The number of nodes of a tree. A leaf has none. -/def Tree.size : Tree → Nat | .nil => 0 | .node l r => l.size + r.size + 12 definitions in 1 chapter · reading list
1.1 Shapes
A tree stores no keys. Only its shape matters here.
/-- A binary tree shape: a leaf, or a node with a left and a right subtree. Keys are not stored. -/inductive Tree where | nil : Tree | node (left right : Tree) : Tree1.2 Size
The size counts nodes, not leaves.
/-- The number of nodes of a tree. A leaf has none. -/def Tree.size : Tree → Nat | .nil => 0 | .node l r => l.size + r.size + 1/-- A node has one more node than its two subtrees together. -/theorem size_node (l r : Tree) : (Tree.node l r).size = l.size + r.size + 1 := … by simp [Tree.size] <;> omegaStatement reads only
Abstract.lean and its importsTry it
What is the size of a node whose two subtrees are empty?