Binary Trees in Python
Chapter 47: Binary Trees
7 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Tree words: root, child, leaf, height, depth
A tree is a set of nodes joined by branches, where one node, the root, has no parent and every other node has exactly one; in a binary tree each node has at most two children, a left one and a right one.
Depth-first traversals: preorder, inorder, postorder
A depth-first traversal walks a node's left subtree completely, then its right subtree completely, and visits the node itself either before both (preorder), between them (inorder) or after both (postorder).
Breadth-first: level order with a queue
A breadth-first traversal keeps the nodes waiting to be visited in a queue: it takes the node at the front, visits it, and puts that node's children at the back, so every level is visited before the level below it.
Tree recursion patterns: height, diameter, same tree, invert
Solve a tree problem by deciding what the answer is for an empty tree, and how to build a node's answer from its left and right subtrees' answers; recursion does the rest.
Answers that climb up: lowest common ancestor and the maximum path sum
A postorder function returns something small up the tree ("I found p or q", or "the best path going down from me") and, while it is at a node, looks at both children's answers together to update the overall answer.
Rebuilding and saving trees: from two walks, and to a string
In preorder the first value is always the root, and in inorder the root splits the values into its left and right subtrees, so the two walks together rebuild the tree; and a preorder walk that writes # for every empty child is enough on its own, because the marks say exactly where each subtree ends.
Walking a tree with your own stack
A recursive traversal can be rewritten with a list used as a stack, which holds the nodes still waiting to be finished, so the order stays the same and the depth limit disappears.