Demo Trees in Lean
Tracks
Check a result Declarations Bibliography Lean source

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 00.

The Lean definitions
inductiveTreeno axiomsAbstract.lean:14
/-- 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
defTree.sizeno axiomsAbstract.lean:19
/-- 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
2 definitions in 1 chapter · reading list

1.1 Shapes

A tree stores no keys. Only its shape matters here.

inductiveTreeno axiomsAbstract.lean:14
/-- 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

1.2 Size

The size counts nodes, not leaves.

defTree.sizeno axiomsAbstract.lean:19
/-- 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
theoremsize_nodepropextAbstract.lean:58
/-- 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] <;> omega
Statement reads only Abstract.lean and its imports
Try it

What is the size of a node whose two subtrees are empty?