Trees

Watch a tree vertex by vertex: the preorder, inorder and postorder traversals with the order in which each vertex is visited, the binary search tree built as you insert, the tree of an expression with its Polish notation and the evaluation with a stack, and the Huffman code joining weights two by two. It works in your browser, on your phone too.

How to use it

  1. Start with «Preorder: the root first»: the tree from the theory, a(b(e,f),c,d(g,h)). Press «Next step» and watch each vertex being written down, with its position next to it.
  2. Carry on with the inorder and postorder of the same tree: only the moment the root is visited changes.
  3. In «The BST of the sign-ups» eight names arrive and each one goes down comparing until it hangs; at the end, the inorder comes out sorted.
  4. In «The tree of an expression», (3·v + e)·2 − d gives its prefix, infix and postfix notations, and the postfix form is evaluated with a stack. Then «The Huffman code» joins the app’s alerts two by two and «Decoding 0011010» goes down the tree bit by bit.
  5. In «Your tree» type a tree such as a(b,c), an expression (with values, if you want to evaluate it), a list of data for the BST or some symbols with their weights (and some bits to decode). Press «Explain it slowly» at any step to see the idea in more detail.

What it draws

Each vertex is a circle (or a capsule, if its name is long) and the root is at the top. In coral, the vertex of the step and the path from the root to it; in green, the ones already visited, with their position. In the Huffman code, each symbol has its weight underneath (or its code, at the end) and each branch its 0 or 1. At the top, in the strip, goes the Python line for each step with its result: visita("c"), insertar(abb, "Lola"), pila.append(12 + 2) or huffman(frec).

The criteria it follows

  • The inorder of a tree with more than two children is the one in the notes: the first subtree, the root and then the rest of the subtrees.
  • In the BST, smaller to the left and bigger to the right; names are compared alphabetically and numbers as numbers. A repeated item is not inserted.
  • In infix only the brackets needed to keep the same calculation are written.
  • In Huffman the two lightest of everything that is left are joined; the heavier goes left (0) and the lighter right (1), as in the slides. With another convention the 0s and 1s change, but the lengths do not.

For the exam

The tree topic quizzes ask you to write a traversal, turn an expression into Polish notation, build a BST and its inorder, and work out the Huffman code with its average length. Here you can see all of that in motion; the theory and the exercises are in trees. The challenge below gives you traversals, postfix expressions to evaluate and Huffman codes, new every time.