๐Ÿ“˜ CodingMarble Learn

Trees in Data Structures: Binary Trees and Binary Search Trees

A tree stores data in nodes joined by edges, like a family tree turned upside down. The top node is the root, nodes with no children are leaves. A tree with n nodes has n โˆ’ 1 edges. Depth of a node is its distance (in edges) from the root; height of the tree is the longest root-to-leaf path. In a binary tree every node has at most two children. A binary search tree (BST) keeps smaller keys on the left and bigger keys on the right, so searching skips half the tree at each step. Traversals visit every node: pre-order (root, left, right), in-order (left, root, right) and post-order (left, right, root). In-order on a BST gives sorted output.

๐ŸŽฌ Step-by-step story

  1. A tree is made of nodes joined by edges. The top node is the root. Nodes with no children are leaves.
  2. Rows are levels. The root is at level 0. The height is the longest path from the root down to a leaf.
  3. In a binary tree each node has at most two children: a left child and a right child. We can store any rooted tree as a parent list.
  4. In a binary search tree, smaller keys go left and bigger keys go right. Search 60: go right, then left. Found in 3 checks.
  5. A traversal visits every node once. In-order (left, root, right) on a BST gives the numbers in sorted order.
  6. Your turn: insert numbers into the BST. Predict where each one lands before you press Insert.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

๐Ÿค” Common doubts, cleared

Why is the root drawn at the top if real trees grow up?

It is just a convention: we read from top to bottom, so the start (root) is placed first.

Is height counted in nodes or edges?

Here we count edges, so a lone root has height 0. Some books count nodes; always check the rule.

Is every binary tree a BST?

No. A BST is a binary tree that also follows the small-left, big-right rule.

Why is in-order sorted for a BST?

It prints everything smaller (left) before the node and everything bigger (right) after it, at every node.

Can a BST be slow?

Yes. Insert numbers in sorted order and it becomes a chain. Try it in free play.

What is a tree?

A tree is a way to store data that has a top-down shape. Each item sits in a node. Nodes are joined by edges.

A tree has no loops, and there is exactly one path between any two nodes. With n nodes it always has n โˆ’ 1 edges.

Levels, depth, height and degree

Depth of a node = number of edges from the root to it. The root has depth 0. All nodes at the same depth form a level.

Height of a tree = the largest depth of any leaf. A tree with only a root has height 0. (Some books count nodes instead of edges, so they add 1. Always check which rule is used.)

Degree of a node = number of children it has.

Storing a rooted tree: the parent array

Number the nodes 1 to n. For each node, write its parent; write 0 for the root. Example: nodes 1..5 with parent array [0, 1, 1, 2, 2] means 1 is the root, 2 and 3 are children of 1, and 4 and 5 are children of 2. Leaves are nodes that never appear in the array as a parent (here 3, 4, 5). Another way is a child list: for each node, list its children.

Binary trees

A binary tree is a tree where each node has at most two children, called the left child and the right child.

Level k of a binary tree can hold at most 2k nodes. In code, a node is usually a record with key, left and right (links that are empty/None when there is no child).

Binary search trees (BST)

A BST is a binary tree with one rule at every node: all keys in the left subtree are smaller, all keys in the right subtree are bigger.

Search

Start at the root. If the key equals the node, stop. If it is smaller, go left; if bigger, go right. If you reach an empty link, the key is not there.

Insert

Search for the key; where the search falls off the tree, attach a new leaf.

In a balanced BST with n nodes, search takes about log2 n steps (1,000,000 keys โ†’ about 20 checks). If keys are inserted already sorted (10, 20, 30, โ€ฆ) the BST becomes a long chain and search becomes slow (n steps).

Tree traversals

A traversal visits every node exactly once.

def inorder(node):
    if node is None:
        return
    inorder(node.left)
    print(node.key)
    inorder(node.right)

Try it at home

Write the numbers 50, 30, 70, 20, 40, 60, 80 on seven slips of paper. Place them on the floor one at a time using the BST rule. Then pick up the slips in in-order and check they come out sorted. Now try inserting 10, 20, 30, 40: what shape do you get?

Key formulas and definitions

Worked examples

1. A tree has 12 nodes. How many edges does it have?

Edges = nodes โˆ’ 1 = 12 โˆ’ 1 = 11.

2. Parent array for nodes 1..6 is [3, 3, 0, 1, 1, 2]. Find the root, the leaves and the height.

Root = node 3 (parent 0). Children of 3: 1 and 2. Children of 1: 4 and 5. Child of 2: 6. Leaves: 4, 5, 6 (never a parent). Depths: 3โ†’0; 1,2โ†’1; 4,5,6โ†’2. Height = 2.

3. Insert 40, 20, 60, 10, 30, 50 into an empty BST and give the in-order and pre-order traversals.

40 is the root. 20 < 40 goes left; 60 right. 10 < 40, < 20: left of 20. 30: left of 40, right of 20. 50: right of 40, left of 60. In-order: 10, 20, 30, 40, 50, 60 (sorted). Pre-order: 40, 20, 10, 30, 60, 50.

4. A perfect binary tree has height 3. How many nodes and how many leaves?

Nodes = 2^(3+1) โˆ’ 1 = 15. Leaves are all on level 3: 2^3 = 8.

Common mistakes

Practice quiz

1. A node with no children is called a:
2. A tree with 20 nodes has how many edges?
3. In a BST, where is a key smaller than the root stored?
4. Which traversal of a BST gives sorted output?
5. Maximum number of nodes at level 3 of a binary tree:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is a tree in data structure?

A non-linear structure of nodes joined by edges, with one root at the top and no loops. It suits data with a hierarchy, like folders.

What is the difference between a binary tree and a binary search tree?

A binary tree only limits each node to two children. A BST adds an order rule: left subtree smaller, right subtree bigger.

What are the three depth-first traversals?

Pre-order (root, left, right), in-order (left, root, right) and post-order (left, right, root).

Where this is taught

RomaniaClasa a XI-aTrees
Germany (Bavaria)Jahrgangsstufe 12Trees

Learn first

Learn next

Related lessons

All Computer Science lessons