What is Tree Traversal
A traversal visits every node once. Inorder visits the left subtree, then the node, then the right subtree. Preorder visits the node before its children. Postorder visits the node after its children.
1 2 3 inorder 2 1 3 preorder 1 2 3 postorder 2 3 1
Approach
The same tree produces three lists because the visit happens at a different moment. The picture walks inorder and highlights the node being written.
The driver prints the three lists on three lines. The animation follows inorder so each visit is visible on the tree.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each node is entered once and written once. |
| Call stack | O(h) | The recursion is as deep as the tree. |
Implementation
def inorder(node, out):
if not node: return
inorder(node.left, out)
out.append(node.val)
inorder(node.right, out)
def solve(self, root):
inn, pre, post = [], [], []
# fill the three lists, then return them