Binary Tree

Tree Traversal Visualizer

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.

InorderLeft, node, right. On a binary search tree this list comes out sorted.
Preorder and postorderPreorder writes the node before either child. Postorder writes it only after both children have been written.

The driver prints the three lists on three lines. The animation follows inorder so each visit is visible on the tree.

Interactive solution

Inorder visits, with the other two orders in the answer
def inorder(node):
if node is null: return
inorder(node.left)
visit node
inorder(node.right)
preorder visits the node before the children
postorder visits the node after the children
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each node is entered once and written once.
Call stackO(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