easyBinary Trees 0 views

Binary Tree Basics

An introduction to the Node and BinTree building blocks used throughout the Binary Trees series, plus a sample tree these exercises build on.

This is the first exercise in the Binary Trees series. It introduces the two building blocks used throughout the rest of the series -- Node<T> and BinTree<T> -- and constructs one sample tree that later exercises (traversals, height, balancing, and so on) will reuse.

The building blocks

// Node class representing a single node in the binary tree
// Generic type T allows for flexible data storage
public class Node<T> {
    // Data stored in the node
    public T data;
    // Reference to the left child node
    public Node<T> left;
    // Reference to the right child node
    public Node<T> right;

    // Constructor to initialize a node with given data
    public Node(T data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
// Binary tree class that manages a tree structure of nodes
// Uses generic type T that must be comparable for ordering
public class BinTree<T extends Comparable<T>> {
    // Root node of the binary tree
    public Node<T> root;

    // Default constructor initializing an empty tree
    public BinTree() {
        this.root = null;
    }
}

The sample tree

getTree() builds the following 12-node tree, which every later exercise in this series refers back to:

    // Sample Binary Tree
    //
    //                1
    //              /   \
    //             2     3
    //            / \     / \
    //           4   5 6   7
    //          /   /         / \
    //         8   9      10  11
    //                               \
    //                               12
    //
 
See the Solutions tab for the Java implementation of `getTree()`.

This is a foundational exercise -- there are no hints or graded test cases for it, since there's no single function output to check. Later exercises in this series (traversals, depth, balancing, search) will operate on this same tree and will have graded test cases.

Constraints

  • The tree has exactly 12 nodes with unique integer values 1 through 12.
  • This structure is reused as input for later Binary Trees exercises.

Follow-up

Later exercises in the Binary Trees series (traversals, depth/height, balancing, search) will operate on this same tree.

Hints

No hints yet.

Companies

No companies reported yet.

Discussion

Sign in to join the discussion.

Loading discussion...

Test results

This question doesn't have a code exercise.