Trees in practice
After this: Say what the libraries give you, and when recursion goes too deep.
On this page · 8 sections · 3 checks
You can now build a tree, walk it in four orders, and work out its size and height. This lesson looks at real programs. What do Python and Java give you? Where do trees turn up? And when does a recursive walk stop working?
Trees you build yourself
Neither Python nor Java has a ready-made binary tree class for you to import. You do not need one. The Node class from The parts of a tree is all of it: a value and two links. When a coding problem gives you a tree, this is the class it means. The four walks and the three properties are your tools.
Trees you are given
Trees still appear in many libraries. One common case is a document, such as a web page. Take this small piece of HTML, which is a list of two items, where the second item has a bold part: <ul><li>one</li><li>two<b>!</b></li></ul>. Each tag sits inside another tag, so the document is a tree.
ul├── li "one"└── li "two" └── b "!"The standard libraries can walk this tree in preorder, as you did in Walking a tree with recursion. There is one change. A document node can have any number of children, not only a left and a right. So the two recursive calls become a loop over the children.
import xml.etree.ElementTree as ET
page = ET.fromstring("<ul><li>one</li><li>two<b>!</b></li></ul>")print([el.tag for el in page.iter()]) # iter() is a preorder walk['ul', 'li', 'li', 'b']
import java.io.ByteArrayInputStream;import java.util.*;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;
public class Dom { // A preorder walk, on a node with any number of children. static void tags(org.w3c.dom.Node node, List<String> out) { if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) out.add(node.getNodeName()); for (org.w3c.dom.Node c = node.getFirstChild(); c != null; c = c.getNextSibling()) tags(c, out); }
public static void main(String[] args) throws Exception { String html = "<ul><li>one</li><li>two<b>!</b></li></ul>"; Document page = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(html.getBytes())); List<String> out = new ArrayList<>(); tags(page.getDocumentElement(), out); System.out.println(out); }}[ul, li, li, b]
Here is how to read it.
- In Python,
page.iter()is the preorder walk, and the library writes it for you.el.tagis the name of each tag. - In Java,
tagsis the preorder walk. It visits the node, then loops over the children, usinggetFirstChildand thengetNextSiblingto move along them. Java's XML library has its own class calledNode, so the code writes its full name,org.w3c.dom.Node, to tell it apart from ours.
Here are two more trees you may meet.
- Source code. Python's
ast.parseturns source code into a tree, and most compilers do the same. In2 + 3 * 4, the+is at the root and the*is below it. That is how the program knows to multiply first. - Files. A file system is a tree. Python's
os.walkand Java'sFiles.walkboth go through it from the top down: a folder before what is inside it.
A tree you cannot touch
Java's TreeMap and TreeSet have a tree inside them, but you cannot walk it yourself. They use a red-black tree, a kind of tree that keeps its own shape tidy and its keys sorted. You can ask for keys and values, but you never get a node, a left or a right. Python's standard library has nothing like it. When you need order in Python, you can use a dict with sorted(), or keep a sorted list with the bisect module.
ages = {"cal": 3, "ann": 1, "bea": 2}for name in sorted(ages): # no tree map in Python: sort when you need order print(name, ages[name])ann 1 bea 2 cal 3
Map<String, Integer> ages = new TreeMap<>(Map.of("cal", 3, "ann", 1, "bea", 2));for (var e : ages.entrySet()) // a red-black tree inside: sorted iteration, no left or right exposed System.out.println(e.getKey() + " " + e.getValue());ann 1 bea 2 cal 3
When recursion goes too deep
You saw that a recursive walk keeps a frame for each node on the path from the root. So the stack gets as deep as the tree is tall. Whether that is a problem depends on the shape of the tree.
- A has about the same height on both sides of every node. A balanced tree of a million nodes is about twenty levels tall. Twenty frames is no problem.
- A is a tree where every node has at most one child. A chain of ten thousand nodes is ten thousand levels tall, so it needs about ten thousand frames.
Python stops at 1,000 frames by default, with a RecursionError. Java's limit depends on the size of its thread stack, but a deep enough chain reaches it too, with a StackOverflowError.
Chains are not rare. If you insert sorted values into a plain binary search tree, you get a chain, and the next tutorial shows this on purpose.
Walking with your own stack
The fix is to keep the stack yourself, as a list of nodes in your own code. A list can grow far larger than the call stack can. This uses the stack from stacks and queues: the last item added is the first item taken.
Here is the method.
- Push the root.
- Pop a node, and visit it.
- Push its right child, and then its left child.
- Go back to step 2. Stop when the stack is empty.
Why does the right child go first? The last node pushed is the first node popped. We want to go left first, so the left child must be pushed last. Here it is on the example tree. The top of the stack is on the right.
| Step | Pop and visit | Push | Stack afterwards |
|---|---|---|---|
| Start | 1 | 1 | |
| 1 | 1 | 3, 2 | 3, 2 |
| 2 | 2 | 5, 4 | 3, 5, 4 |
| 3 | 4 | 3, 5 | |
| 4 | 5 | 3 | |
| 5 | 3 | 6 | 6 |
| 6 | 6 | (empty) |
The visited order is 1 2 4 5 3 6, which is preorder. It has the same shape as the level order method, with a stack in place of the queue.
def preorder_iterative(root): out = [] stack = [root] if root else [] while stack: node = stack.pop() out.append(node.value) if node.right: stack.append(node.right) # right first, so that left is popped first if node.left: stack.append(node.left) return outstatic List<Integer> preorderIterative(Node root) { List<Integer> out = new ArrayList<>(); Deque<Node> stack = new ArrayDeque<>(); if (root != null) stack.push(root); while (!stack.isEmpty()) { Node node = stack.pop(); out.add(node.value); if (node.right != null) stack.push(node.right); // right first, so that left is popped first if (node.left != null) stack.push(node.left); } return out;}The loop matches the steps above: pop, visit, push right, push left. A missing child is not pushed.
print(preorder_iterative(root))[1, 2, 4, 5, 3, 6]
System.out.println(preorderIterative(root));[1, 2, 4, 5, 3, 6]
Watch it happen
Here is a chain of four. Measure its height, then run preorder and watch the stack.
- Measure the heightHeight. There are four nodes in a line, so the path from the root down to 4 has three edges.
- Preorder traversal
Run an operation to begin.
Check yourself
You need a binary tree in Python or Java. Where does the class come from?
A recursive preorder runs on a chain of 5,000a million nodes, each with at most a right child. What happens?
The preorder with your own stack pushes the right child before the left. Why?
Connect
- Say that neither standard library has a binary tree class you shape yourself, and name where trees turn up anyway: documents, source code and file systems.
- Explain why Java's TreeMap is not a tree you can walk, and what Python offers when you need order.
- Say when a recursive walk runs out of stack, and replace it with your own stack of nodes.