Skip to the content. Back to Chapter 2

Trees

What is a tree?

Definitions

              root
subtree  ,--'      `--.
/   parent     \     parent
|  /   |  \    |    /      \
\leaf leaf leaf/ child    leaf

What is a binary tree?

Implementation

Traversing a binary tree

Image representing in-order traversal
This represents in-order traversal, and the output is the sorted list; 4,5,8,12,14,17,18,22,25,30

Image representing pre-order traversal
This represents pre-order traversal, and the output is 17,8,4,5,12,14,22,19,30,25

Image representing post-order traversal
This represents post-order traversal, and the output is 5,4,14,12,8,19,25,30,22,17

Traversing a binary tree (algorithm)

PROCEDURE preorder_traverse(NODE p) DO
    PRINT p.data
    IF p.left IS NOT NULL DO
        preorder_traverse(p.left)
    END IF
    IF p.right IS NOT NULL DO
        preorder_traverse(p.right)
    END IF
END PROCEDURE
PROCEDURE inorder_traverse(NODE p) DO
    IF p.left IS NOT NULL DO
        inorder_traverse(p.left)
    END IF
    PRINT p.data
    IF p.right IS NOT NULL DO
        inorder_traverse(p.right)
    END IF
END PROCEDURE
PROCEDURE postorder_traverse(NODE p) DO
    IF p.left IS NOT NULL DO
        postorder_traverse(p.left)
    END IF
    IF p.right IS NOT NULL DO
        postorder_traverse(p.right)
    END IF
    PRINT p.data
END PROCEDURE

Exercise

  1. Show how the following data may be stored as a binary tree for subsequent processing in alphabetic order by drawing the tree. Assume that the first item is the root of the tree and the rest of the data items are inserted into the tree in the order given

    magpie, robin, chaffinch, linnet, thrush, blackbird, fieldfare, skylark, pigeon

    •              magpie
                 /        \
          chaffinch       robin
          /     \         /   \
      blackbird linnet pigeon thrush
                /             /
        fieldfare       skylark
      
  2. Show how the data could be represented using three one-dimensional arrays

    • char* data[9] = {"magpie", "robin", "chaffinch", "linnet", "thrush", "blackbird", "fieldfare", "skylark", "pigeon"};
      int left_ptrs[9] = {2, 8, 5, 6, 7, -1, -1, -1, -1};
      int right_ptrs[9] = {1, 4, 3, -1, -1, -1, -1, -1, -1};
      
  3. List the order that the nodes would be visited in during:

    1. Pre-order traversal
      • magpie, chaffinch, blackbird, linnet, fieldfare, robin, pigeon, thrush, skylark
    2. In-order traversal
      • blackbird, chaffinch, fieldfare, linnet, magpie, pigeon, robin, skylark, thrush
    3. Post-order traversal
      • blackbird, fieldfare, linnet, chaffinch, pigeon, skylark, thrush, robin, magpie

In a BST, what kind of traversal will retrieve the contents in sorted order?

How do we find an object in a BST?