Recursion and Trees
This chapter is about trees. A tree is a linked structure defined recursively: a node holding a value, with zero or more smaller trees beneath it that branch apart and never rejoin.
After reading this chapter, you should be able to:
- Draw the call tree of a recursive run, and tell a chain (one recursive call) from a branching tree (several)
- Give recursive definitions of a linked list, a tree, and a binary tree
- Identify the parts of a tree, such as the root, children, leaves, and subtrees
- Represent a binary tree with
Nodeobjects and write recursive methods over it, such as size, height, and depth - Write and trace the recursive pre-order, in-order, and post-order traversals of a binary tree
- Explain why a recursive traversal produces only depth-first orders
- Implement level-order traversal with a queue
- Choose a traversal order to fit a task on a tree
You can download the accompanying code for this chapter: starter and solution.
Sections
- Revisiting Recursion
- The Call Tree
- A Linked List Is Recursive
- A Tree Is Recursive
- Linked Lists and Trees
- Anatomy of a Tree
- Narrowing to Binary Trees
- From a Definition to a Node
- Counting the Nodes
- Measuring Height
- Measuring Depth
- Traversing the Tree
- Tracing the Three Orders
- Traversing Level by Level
- Trying Recursion
- A Queue of Waiting Nodes
- Level-order in Code
- Traversals in Practice