algoritmauzmanı
Sign in
TREN
6.3Binary Tree with Linked Nodes
Lesson 6.3.3

Preorder traversal

To a tree is to visit every node once. A list had a single path; in a tree the path splits in two at every node, and you have to choose which side goes first. In a traversal a node is visited before its children: root, left, right. In this lesson you write that order as a three-line function.

What you will learn
  • What preorder means: root, left subtree, right subtree
  • The of the recursive function and why it stops at an empty subtree
  • That the call stack grows as tall as the tree
6 minTime O(n)Memory O(h)C · Java · Python

1Idea

Every node is the root of a . So "walk the tree" can be written as "visit the root, walk the left subtree, walk the right subtree". The left and right subtrees are trees too and are walked by the same function. The code is that sentence itself: one print line and two recursive calls.

The is the empty subtree: if root is NULL there is nothing to do and the function returns at once. For a leaf two calls are made, both with NULL, and both end right away. Without the base case the function would try to read the left field of NULL.

On the sample tree the preorder output is 10 20 40 50 30 60. The root is printed first; 30 gets its turn only after the whole subtree of 20 is done. Preorder is used to copy a tree in the same shape: since roots come first, the tree can be rebuilt from the top down. Printing a folder tree with indentation is a preorder too.

The same traversal is written with the same three lines in an array tree; the only difference is the index 2*i+1 in place of root->left.

2Step by step

The drawing walks the sample tree in preorder. The orange node is the one being printed, the green ones were printed earlier. The calls that have not finished are shown under the drawing, with the running one on top. Calls on NULL return at once, so they are not shown.

100x2a0200x2c8300x2f0400x318500x340600x368root
Call stack
  1. Start. preorder(root) has not been called yet; the output is empty.
  2. The first call starts at the root. The root comes first: 10 is printed. Output: 10.
  3. Next comes the left subtree. preorder(20) is called and 20 is printed. Output: 10 20.
  4. The left of 20 is 40: 40 is printed. Both children of 40 are NULL; both calls return at once. Output: 10 20 40.
  5. Back in 20, the right subtree is walked: 50 is printed. Output: 10 20 40 50.
  6. The subtree of 20 is done; back in 10. Next comes the right subtree: 30 is printed. Output: 10 20 40 50 30.
  7. The left of 30 is 60: 60 is printed. The right of 30 is NULL. Output: 10 20 40 50 30 60.
  8. All calls are finished. Every node was printed once; the preorder output is 10 20 40 50 30 60.

struct TreeNode {    int data;    struct TreeNode* left;    struct TreeNode* right;}; void preorder(struct TreeNode* root) {    if (root == NULL) return;       // empty subtree: base case    printf("%d ", root->data);      // 1. root    preorder(root->left);           // 2. left subtree    preorder(root->right);          // 3. right subtree}
class TreeNode {    int data;    TreeNode left, right;    TreeNode(int data) { this.data = data; }} void preorder(TreeNode root) {    if (root == null) return;           // empty subtree: base case    System.out.print(root.data + " ");  // 1. root    preorder(root.left);                // 2. left subtree    preorder(root.right);               // 3. right subtree}
class TreeNode:    def __init__(self, data):        self.data = data        self.left = None        self.right = None def preorder(root):    if root is None:            # empty subtree: base case        return    print(root.data, end=" ")   # 1. root    preorder(root.left)         # 2. left subtree    preorder(root.right)        # 3. right subtree

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

3Complexity

Time
O(n)

Every node is printed once; each node makes two calls, some of which end at once on NULL.

Memory
O(h)

The call stack grows as long as the path from the root to the deepest leaf: the height h of the tree.

In a balanced tree h is about log n. In a tree whose nodes all sit on one branch, h = n and the stack takes room.

4Common mistake

A common mistake is writing the base case by checking the children:

void preorder(struct TreeNode* root) {    printf("%d ", root->data);    if (root->left != NULL) preorder(root->left);    if (root->right != NULL) preorder(root->right);}

This code works on a non-empty tree but crashes on an empty one, at the first line of preorder(NULL). Writing the base case at the top as root == NULL is shorter and covers the empty tree too. Another mistake is putting the print line between the two calls: then the function prints inorder, not preorder.

5Try it

A tree has root 1, left child 2, right child 3, and 4 is the left child of 2. What is its preorder output?

Show the answer

The answer is B. The root 1 is printed first. Then the whole left subtree is walked: 2 and its left child 4. The right subtree, 3, comes last.

What is always the first element of a preorder output?

Show the answer

The answer is B. In preorder a node is printed before its subtrees. The first call is made on the root, so the first value printed is the root.

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