CSCI C343 Data Structures Spring 2025

Binary Trees

Motivation

Taking stock with respect to Flood-it! and the Set interface

  array linked list sorted array
membership test O(n) O(n) O(log(n))
insertion O(1)* O(1) O(n)

BinaryNode and BinaryTree Classes

class BinaryNode<T> {
	T data;
	BinaryNode<T> left;
	BinaryNode<T> right;

	BinaryNode(T d, BinaryNode<T> l, BinaryNode<T> r) {
			data = d; left = l; right = r;
	}
}

public class BinaryTree<T> {
	BinaryNode<T> root;

	public BinaryTree() { root = null; }
	// ...
}

We can traverse a binary tree in several different ways:

preorder(node) { output node.data preorder(node.left) preorder(node.right) }

inorder(node) { inorder(node.left) output node.data inorder(node.right) }

postorder(node) { postorder(node.left) postorder(node.right) output node.data }

Example:

             10
            / \
           /   \
          5     14
         / \     \
        2   7     19

        pre:  10,5,2,7,14,19
        in:   2,5,7,10,14,19
        post: 2,7,5,19,14,10

Recursion Tree written as an “outline”