ITC 120 › Midterm › Trees and BSTs
Trees and BSTs · Lesson 1 of 6
Trees and Binary Trees
This lesson teaches:Data structureOur first non-linear data structure: nodes that branch out, like folders inside folders.
By the end, you can:
- explain how a tree node is like a linked-list node with more than one
next; - name the root, parents, children, siblings, leaves, ancestors, descendants, and subtrees in a given tree, and find any node's depth and height;
- tell whether a tree is a binary tree, and read its
leftandrightreferences in Java; - write the Java lines that build a binary tree from a drawing.
You need: the Linked lists lesson, and scratch paper.
Part 1 · From lists to trees
Some data branches out
You already know nodes from linked lists. Think of a train: each car is a node. It carries cargo (its data) and has one hook (next) to the car behind it. The last car has nothing hooked to it, so its next is null.
In Java, that car is this class: one value, one link.
class Node {
int data;
Node next; // one link
Node(int value) {
data = value;
next = null;
}
} But some data does not line up in one chain. Open the Files app on your phone: Internal storage holds DCIM, Download, and Documents, and DCIM holds Camera and Screenshots. One folder can hold many folders. Draw it out, and it branches like an upside-down tree:
The folder at the top is the root. A folder inside another is its child. Folders with nothing inside are leaves. You will learn all these terms in Part 2.
Tree
A tree is a non-linear data structure made of nodes connected by edges, arranged in levels from top to bottom (a node's level is how many edges it is from the root, so the root is level 0). It follows three rules:
- One node is at the top: the root.
- Every other node has exactly one parent.
- A node can have any number of children.
Where you see trees in IT
Folders on a computer, the categories in an online shop (Electronics → Phones → Android), an organization chart, and a family tree are all trees.
Part 2 · Terminology
Tree terminology
Trees come with their own vocabulary. Most words come from family trees. Explore them first, then read the summary table below.
Tree terminology explorer
Tap any node to see its family. Or tap a term below to highlight it in the tree.
Tap a node or a word.
Here are all the terms, with examples from the explorer tree. Tap any row to see it in the tree (on a computer, just point at the row). The colors in the Example column match the colors in the tree.
| Term | Meaning | Example |
|---|---|---|
| Node | holds one value | A |
| Edge | the line that links a parent to its child (only the line, not the nodes) | the line between A and B |
| Size | the number of nodes | 10 nodes (and 9 edges) |
| Root | the top node; the only one with no parent | A |
| Parent / child | a node directly above / below another | B is the parent of D, E, F |
| Siblings | nodes with the same parent | D, E, F (children of B); also B and C, and H and I |
| Leaf | a node with no children | D, H, J, F, G |
| Internal node | a node with at least one child | A, B, C, E, I |
| Ancestor / descendant | going down from X to Y: X is an ancestor of Y, Y is a descendant of X | A, B, and E are ancestors of H |
| Subtree | a node plus everything below it | the subtree rooted at B: B, D, E, H, I, J, F |
| Depth of a node | edges from the root down to the node | depth of E = 2 (A → B → E) |
| Height of a node | edges on the longest path from the node down to a leaf | height of E = 2 (E → I → J; E → H is shorter, so it does not count) |
| Height of the tree | the height of the root | 4 (A → B → E → I → J) |
| Depth of the tree | the depth of its deepest node: the same number as the height of the tree | 4 (J is the deepest node) |
Do not mix them up: depth vs. height
Depth looks up to the root: how far down is this node? Height looks down to the leaves: how tall is the tree under this node? Both count edges, not nodes. The root has depth 0; every leaf has height 0.
Depth of E = 2
Count the edges from the root down to E: A → B → E. There is only one way up, so depth is easy.
Height of E = 2
Count the edges from E down to its deepest leaf: E → I → J. E → H is only 1 edge. Height always takes the longest path down.
Look at G → K → L → M in the height picture. That path reaches lower than J, but it is not below E, so it has nothing to do with E's height. Only the leaves under E count: H and J. (We added K, L, and M under G just for these two pictures.)
Part 3 · Binary trees
At most two children
Binary tree
A binary tree is a tree in which every node has at most two children: a left child and a right child.
So the explorer tree from Part 2 is not a binary tree: B has three children (D, E, and F). One node with three or more children is enough to break the rule. In a binary tree, every node has 0, 1, or 2 children.
Left and right are two different slots
Every node in a binary tree has two separate child slots: left and right. Think of your left and right shoes: they are a pair, but you cannot swap them. A child always sits in one specific slot, and a slot with nothing in it is null (the small dashed boxes below).
Tree 1
30 is in the left slot.root.left is 30, root.right is null.
Tree 2
30 is in the right slot.root.left is null, root.right is 30.
Both trees hold the same two values, 50 and 30. But a program that asks for root.left gets 30 from Tree 1 and null from Tree 2. Same values, different slots: these are two different binary trees.
A binary-tree node in Java
Each node is an object made from a class, with one value and two child references. Compare it with the linked-list Node class from Part 1 : next became left and right. Step through the class to see what each line means:
Reading the TreeNode class
Tap any line to see what it does, or use Next to go through the code in order.
class TreeNode { ... } describes what every tree node will look like. It is a class: only a blueprint (like the polvoron mold in the Linked lists lesson), so no node exists yet. In these pictures, we draw a node as a box split into parts, one part per variable inside it. The box is just a drawing to help you see it. Java does not draw anything.
1class TreeNode { 2 int data; 3 TreeNode left; // left child 4 TreeNode right; // right child 5 6 TreeNode(int value) { 7 data = value; 8 left = null; // no children yet 9 right = null;10 }11} Here is the difference in pictures, then in a table:
Linked-list node
Binary-tree node
| Singly linked list | Binary tree |
|---|---|
head refers to the first node | root refers to the top node |
next: one link | left and right: two links |
null: no next node | null: no child on that side |
Careful
left and right are not previous and next. Both point down, to children. A missing child is null; a leaf has both sides null.
Building a tree in Java
To build a tree, make nodes with new and store them in the child slots. Step through it: watch which slot each line fills.
Building a tree, line by line
Tap any line to see what it does, or use Next to go through the code in order.
Make a node holding 8. The variable root refers to it. Its left and right are null (the small dashed boxes).
1TreeNode root = new TreeNode(8); 2root.left = new TreeNode(3); 3root.right = new TreeNode(10); 4root.left.left = new TreeNode(1); Now you: read the code, then draw the tree
No walkthrough this time. Draw it on paper first, then check.
TreeNode root = new TreeNode(50);
root.left = new TreeNode(30);
root.right = new TreeNode(70);
root.left.right = new TreeNode(40); Tip: in the code, read each dot (.) from left to right. root.left.right means: start at root, go to its left, then go to that node's right.
Draw it on paper first. Then build your drawing below and tap Check my tree.
Build your drawing
Drag a value onto a dashed spot. On a phone, you can also tap a value, then tap a spot. Tap a leaf to take it back.
Check your drawing
40 is the right child of 30. 30 has no left child (null).
Same values, different shapes
height 2
height 6: shaped like a chain
The same seven values can make a short, bushy tree or a tall chain. Shape matters: you will see why in the next lessons (and again in AVL trees).
Properties of a binary tree
Each node has at most two children, so each level can hold at most twice as many nodes as the level above it. Adding up the levels gives the most nodes a tree of that height can hold:
| Level | Most nodes on this level | Most nodes in a tree of this height |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 2 | 1 + 2 = 3 |
| 2 | 4 | 3 + 4 = 7 |
| 3 | 8 | 7 + 8 = 15 |
So 7 nodes fit in height 2 only when every spot is filled, like the bushy tree above. The fewest nodes for height h is h + 1: a chain. And whatever its shape, a tree with n nodes has n − 1 edges (every node except the root has one edge up to its parent).
Build-a-tree challenges
Drag values onto the dashed spots (or tap a value, then tap a spot). Tap a leaf to take it back. The orange line shows the longest path from the root: that is the height.
Part 4 · Your turn
Label a tree, build a tree
- Root?
- Leaves?
- Parent of R?
- Sibling of B?
- Ancestors of S?
- Depth of L?
- Height of T?
- Size? Edges?
- Is this a binary tree? Why?
Show the answers
- M
- B, L, Q, S
- T
- L
- R, T, M
- 2
- 2 (T → R → Q)
- 8 nodes, 7 edges
- Yes: every node has at most 2 children (T has only one).
Your coding task: build a tree in Java
In Part 3, you read code and drew the tree. Now go the other way: here is the drawing, and you write the code. Finish buildTree in about 5 lines where it says YOUR CODE, using the TreeNode class from Part 3.
The method at is given, so you can check your tree. Read at(root, "LR") as root.left.right: each L means "go left," and each R means "go right." Run it: each printed line must match its comment.
1class TreeNode {
2 int data;
3 TreeNode left;
4 TreeNode right;
5
6 TreeNode(int value) {
7 data = value;
8 left = null;
9 right = null;
10 }
11}
12
13public class Main {
14 // Builds the tree in the picture and returns its root.
15 static TreeNode buildTree() {
16 TreeNode root = new TreeNode(50);
17 // YOUR CODE: put 30, 70, 20, 40, and 80 in their slots.
18 // 50
19 // / \
20 // 30 70
21 // / \ \
22 // 20 40 80
23
24 return root;
25 }
26
27 // Given (you do not need to change it): follows a path of
28 // L (left) and R (right) from the root, and returns the value
29 // there, or "null" if there is no node.
30 static String at(TreeNode root, String path) {
31 TreeNode current = root;
32 for (int i = 0; i < path.length(); i++) {
33 if (current == null) {
34 return "null";
35 }
36 if (path.charAt(i) == 'L') {
37 current = current.left;
38 } else {
39 current = current.right;
40 }
41 }
42 if (current == null) {
43 return "null";
44 }
45 return "" + current.data;
46 }
47
48 public static void main(String[] args) {
49 TreeNode root = buildTree();
50 System.out.println(at(root, "")); // expected: 50
51 System.out.println(at(root, "L")); // expected: 30
52 System.out.println(at(root, "R")); // expected: 70
53 System.out.println(at(root, "LL")); // expected: 20
54 System.out.println(at(root, "LR")); // expected: 40
55 System.out.println(at(root, "RR")); // expected: 80
56 System.out.println(at(root, "RL")); // expected: null
57 }
58} ▶ This program runs as is. Try it in the Programiz online compiler: tap Copy, paste it there, and press Run.
Show one possible answer
1static TreeNode buildTree() {
2 TreeNode root = new TreeNode(50);
3 root.left = new TreeNode(30);
4 root.right = new TreeNode(70);
5 root.left.left = new TreeNode(20);
6 root.left.right = new TreeNode(40);
7 root.right.right = new TreeNode(80);
8 return root;
9} Output, one per line: 50, 30, 70, 20, 40, 80, null.
Make a parent before its children. root.left.left = ... means "go to root's left node, then store the new node in its left slot." If root.left is still null, there is no node to go to, and Java throws a NullPointerException, the same error as using a null reference in the Linked lists lesson.
Nothing is stored in 70's left slot, so it stays null, and at(root, "RL") prints null.
Other orders work too, as long as each parent comes first: for example, 30, 20, 40, then 70, 80.
Part 5 · Check yourself
Self-check
Not graded. Tap an answer to see if you got it, and read why.
-
Which node has no parent?
The root is the top node and the only node with no parent.
-
A node with no children is called:
A leaf has no children. An internal node has at least one.
-
In the explorer tree, what is the depth of E?
Depth counts edges from the root down: A → B → E is 2 edges.
-
In the explorer tree, what is the height of E?
Height takes the longest path down: E → I → J is 2 edges. E → H is only 1, so it does not count.
-
A tree has 12 nodes. How many edges does it have?
Every node except the root has one edge up to its parent: 12 − 1 = 11.
-
Which statement about a binary tree is true?
A binary tree allows 0, 1, or 2 children per node. Sorting is the extra rule of a binary search tree (next lesson).
-
In Java, what does
root.left.rightrefer to?Read the dots from left to right: start at root, go left, then go right.
-
Are
leftandrightlikepreviousandnextin a linked list?Both
leftandrightpoint down, to the node's two children.
Score: 0 / 8
Key takeaways
- A binary-tree node holds data, a left reference, and a right reference.
- The root is the top node. A leaf has no children.
- Depth: edges from the root to the node. Height: edges from the node down to its deepest leaf.
- A binary tree: every node has at most 2 children.
- A missing child is null.
Next lesson: Binary search trees and BST search.
References
- Programiz, "Tree Data Structure" and "Binary Tree." programiz.com/dsa/trees
- N. Dale, D. T. Joyce, and C. Weems, Object-Oriented Data Structures Using Java, 4th ed. Jones & Bartlett Learning, 2018.
- mycodeschool, "Data structures: Introduction to trees" and "Binary tree" [Videos], YouTube.