You are on page 1of 2

-1-

TREES
Binary tree traversals (walkthroughs)
1. Since a binary tree is a non-linear data structure, we can devise several methods for visiting
the nodes. In each walkthrough, we begin at the root.
a. Inorder walkthrough.
i. Recursively visit the left subtree.
ii. Visit the root.
iii. Recursively visit the right subtree.
b. Postorder walkthrough.
i. Recursively visit the left subtree.
ii. Recursively visit the right subtree.
iii. Visit the root.
c. Preorder walkthrough.
i. Visit the root.
ii. Recursively visit the left subtree.
iii. Recursively visit the right subtree.
d. Backorder walkthrough.
i. Recursively visit the right subtree.
ii. Visit the root.
iii. Recursively visit the left subtree.
Example
Binary search trees (BSTs)
1. Binary trees with an order property. If n is a node in a binary tree, then,
a. key[n] ! key[left-child(n)]. This rule applies recursively, so that key[n] ! all nodes
in the left subtree of n.
b. key[n] < key[right-child(n)]. This rule applies recursively, so that key[n] < all nodes
in the right subtree of n.
Searching in a bst
The order property of a BST makes it ideal for searching (provided the tree is relatively balanced).
For example, we can either find a key k or determine that it is not in the tree in O(lgn) time, where
lg is the log base two function and n is the number of nodes in the tree. Compare this to the O(n)
search time for a bag, sequence or array. Notice the tree must be relatively balanced; that is, the
distance between the levels of the leaf nodes must be relatively small (1 or 2 for example). If a
23
17 3
41 33 7
Pre-order: 23, 17, 41, 3, 33, 7
Post-order: 41, 17, 33, 7, 3, 23
In-order: 41, 17 23, 33, 3, 7
Back-order: 7, 3, 33, 23, 17, 41
Level-order: 23, 17, 3, 41, 33, 7
CSCI 2421 Lecture 21 Fall 2014
-2-
BST is not relatively balanced, the search time increases. In fact, it can degenerate to O(n), the
same as for an array, bag or sequence. A searching algorithm takes advantage of the order property
of the BST.
BST-Search(r, target) // r is the root of a BST
1. Compare target to the key(r). If they are equal, report target found.
2. If target < key(r), continue the search from the left subtree.
3. If target > key(r), continue the search from the right subtree.
4. If at any time during the search in step 2 or 3 the subtree is empty, stop the search
and report, target not found.
Notice we can do processing of the node if we find it. For example, we can display it, pass it to a
function, modify it, etc. Notice also that we will know if a subtree is empty since its parent will
have a NULL field for its left child, right child, or both.
Example of BST
Building BSTs (do in class)
17
7 33
2 23 41

You might also like