Trees (binary trees)
Computer Science · Data structures
Question 1 of 10
0What operator is stored in the root of this expression tree?
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Trees (binary trees) explained
A tree is a data structure made of nodes joined by links, with one special node at the top called the root. In a binary tree, each node has at most two children, usually called the left child and the right child. A node with no children is called a leaf.
Trees represent hierarchies, such as folders on a disk or the structure of an arithmetic expression. A perfect binary tree is one where every level is completely filled, so a perfect tree with 3 levels has nodes. There are standard ways to visit every node. Preorder visits a node, then its left subtree, then its right subtree. Inorder visits the left subtree, then the node, then the right subtree. Postorder visits both subtrees before the node.
A common mistake is to assume a binary tree is always sorted. Only a binary search tree has that ordering rule, and an ordinary binary tree can hold values in any order.
Worked example
Take a tree with root 4. Its left child is 2, with children 1 and 3. Its right child is 6, with children 5 and 7.
- The tree has 3 completely filled levels, so it has nodes.
- Preorder visits 4, 2, 1, 3, 6, 5, 7.
- Inorder visits 1, 2, 3, 4, 5, 6, 7. For a binary search tree, this order would be sorted.
- Postorder visits 1, 3, 2, 5, 7, 6, 4.
What you will practise
41 diagrams. Type the label for each part and get instant feedback.
Example questions
- What is the term for the top node labelled P?
- What is the term for a node with no children, such as the node labelled R?
- What is the connecting line labelled S between two nodes called?
- What is the part of the tree inside the dashed box T called?
- In the lettered tree, which letter labels the root node?
- In the lettered tree, which node is the parent of G?
- In the lettered tree, which node is the right child of C?
- What value is stored at the root of this binary search tree?
…and 33 more.