algoritmauzmanı
Sign in
TREN
6.2Binary Tree with an Array
Lesson 6.2.6

Level-order traversal

A reads the tree floor by floor from the root: the root first, then its children, then its grandchildren, left to right on each floor. With linked nodes this needs a queue. In an array it needs nothing, because the tree was written into the array in exactly this order.

What you will learn
  • What level order is and how it differs from the other three traversals
  • Why level order is a plain loop for a tree in an array
  • Why linked nodes need a queue for it
4 minTime O(n)Memory O(1)C · Java · Python

1Idea

In the insertion lesson nodes always went into the first empty cell: the root first, then level 1 from left to right, then level 2. So the array order is the tree's level order itself. To traverse in level order you just read the array from 0 to count - 1.

The level boundaries are clear from the indexes too: level 0 is only cell 0, level 1 is cells 1 and 2, level 2 is cells 3 to 6. Level k starts at index 2^k - 1.

Preorder, inorder and postorder go deep into the tree: they finish one branch before starting another. Level order goes wide instead: it finishes a floor before going down. In graphs these two ideas are called depth-first and breadth-first search.

With linked nodes the nodes are scattered in memory and siblings do not point to each other. Moving from one floor to the next means keeping the nodes waiting in a queue; level order with linked nodes shows how.

2Step by step

The drawing shows the tree on top and its array below. As i moves left to right through the array, the tree is visited floor by floor, left to right on each floor.

items1001002012013023024034035045046056056i
  1. Start. count is 6. The loop will start at i = 0.
  2. i = 0: the root is printed, 10. Level 0 has a single node. Output: 10.
  3. i = 1: 20 is printed. Level 1 starts here; the level above is fully printed. Output: 10 20.
  4. i = 2: 30 is printed, moving left to right along level 1. Output: 10 20 30.
  5. i = 3: 40 is printed. Level 2 starts here; the level above is fully printed. Output: 10 20 30 40.
  6. i = 4: 50 is printed, moving left to right along level 2. Output: 10 20 30 40 50.
  7. i = 5: 60 is printed, moving left to right along level 2. Output: 10 20 30 40 50 60.
  8. i = 6: the condition 6 < count is no longer true. The loop ends; cell 6 is not part of the tree.
  9. Done. The level order is 10 20 30 40 50 60: the array's own order.

#define CAPACITY 15 struct Tree {    int items[CAPACITY];    int count;}; void levelOrder(struct Tree* t) {    for (int i = 0; i < t->count; i++) {        printf("%d ", t->items[i]);  // the array is already in level order    }}
class ArrayTree {    int[] items;    int count = 0;     ArrayTree(int capacity) {        items = new int[capacity];    }     void levelOrder() {        for (int i = 0; i < count; i++) {            System.out.print(items[i] + " ");  // the array is already in level order        }    }}
class ArrayTree:    def __init__(self, capacity):        self.items = [None] * capacity        self.count = 0     def level_order(self):        for i in range(self.count):            print(self.items[i], end=" ")  # the array is already in level order

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

The loop runs once per node.

Memory
O(1)

Only the variable i is used. There is no recursion and no queue.

With linked nodes level order also takes O(n), but the queue holds up to one full floor, which is about n/2 in the worst case.

4Common mistake

A common mistake is running the loop up to the capacity:

for (int i = 0; i < CAPACITY; i++) {  // wrong: not count    printf("%d ", t->items[i]);}

The cells after count are not part of the tree. They hold old or never-set values, which get mixed into the output. The loop must stop at count.

5Try it

Let the array [5, 3, 8, 1, 4] hold a binary tree in level order (count = 5). What is the level-order output?

Show the answer

The answer is A. The array already holds the tree in level order. The output is the array itself: 5 3 8 1 4.

In a tree stored in an array, at which index does level 3 start? (The root is level 0.)

Show the answer

The answer is B. Level 0 has 1 node, level 1 has 2 and level 2 has 4: 1 + 2 + 4 = 7 cells are used. Level 3 starts at cell 7: 2^3 - 1 = 7.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.