Binary Tree
Representation in Java
Learn how to model binary trees using node classes in Java: from defining the structure to linking nodes into hierarchical data.
What Is a Binary Tree?
A binary tree is a hierarchical data structure where each element, called a node, has at most two children: a left child and a right child. The topmost node is called the root.
Key Terminology
Why Binary Trees Matter
Binary trees power some of the most important structures in computer science. Understanding them unlocks efficient search, sorting, and hierarchical modeling.
The Node Class: Core Building Block
In Java, a binary tree node is modeled as a class with three fields: a value, a reference to the left child, and a reference to the right child.
Anatomy of a TreeNode
Node Class vs. Tree Class
A common design pattern separates the node definition from a tree wrapper that manages the root and provides methods.
| TreeNode (Node) | BinaryTree (Wrapper) | |
|---|---|---|
| Purpose | Stores one value + child links | Manages root reference + tree methods |
| Fields | val, left, right | root |
| Methods | Constructor only (typically) | insert, search, traverse, etc. |
| Instances | One per element in the tree | One per entire tree |
How to Build a Binary Tree
Example 1: Three-Node Tree
Example 2: Five-Node Tree
Example 3: Using a Wrapper Class
Understanding null References
In Java, null means "this reference points to nothing." In binary trees, null marks the absence of a child. It is the base case for recursive algorithms and the signal that you've reached the edge of the tree.
Trees Are Recursive by Nature
Every subtree of a binary tree is itself a binary tree. This recursive structure is why tree algorithms are naturally expressed as recursive methods.
Going Generic: Any Data Type
So far our node stores int values. Using Java generics, we can make the node store any type: String, Double, or custom objects.
Common Mistakes
Summary: Key Concepts at a Glance
| Concept | Definition | Java Code |
|---|---|---|
| Node | One element in the tree | class TreeNode { ... } |
| Value | Data stored in a node | int val; |
| Left child | Reference to left subtree | TreeNode left; |
| Right child | Reference to right subtree | TreeNode right; |
| Root | Top-level node | TreeNode root = new TreeNode(x); |
| Leaf | Node with no children | left == null && right == null |
Question 1 of 5
What are the three fields in a basic TreeNode class for a binary tree?
Question 2 of 5
Given the following code, what does root.left.right evaluate to?
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
root.left.left = new TreeNode(2);
Question 3 of 5
Which statement correctly makes node B the left child of node A?
Question 4 of 5
A leaf node in a binary tree is defined as a node where:
Question 5 of 5
Why is the TreeNode class called a self-referential (recursive) data structure?