ma'am audrey's lessons

ITC 120 › Midterm › Trees and BSTs

Trees and BSTs · Lesson 1 of 6

Trees and Binary Trees

This lesson teaches:Data structure

Our first non-linear data structure: nodes that branch out, like folders inside folders.

By the end, you can:

  1. explain how a tree node is like a linked-list node with more than one next;
  2. name the root, parents, children, siblings, leaves, ancestors, descendants, and subtrees in a given tree, and find any node's depth and height;
  3. tell whether a tree is a binary tree, and read its left and right references in Java;
  4. 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.

102030headdata = the cargonext = the hookno hook after it: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:

FilesInternal storageDCIMCameraScreenshotsDownloadDocumentstap a folder to open what is inside
Internal storageDCIMDownloadDocumentsCameraScreenshotsthe rootparentchildren of DCIMno folders inside:leaves

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:

  1. One node is at the top: the root.
  2. Every other node has exactly one parent.
  3. 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.

ABDEHIJFCG

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.

TermMeaningExample
Nodeholds one valueA
Edgethe line that links a parent to its child (only the line, not the nodes)the line between A and B
Sizethe number of nodes10 nodes (and 9 edges)
Rootthe top node; the only one with no parentA
Parent / childa node directly above / below anotherB is the parent of D, E, F
Siblingsnodes with the same parentD, E, F (children of B); also B and C, and H and I
Leafa node with no childrenD, H, J, F, G
Internal nodea node with at least one childA, B, C, E, I
Ancestor / descendantgoing down from X to Y: X is an ancestor of Y, Y is a descendant of XA, B, and E are ancestors of H
Subtreea node plus everything below itthe subtree rooted at B: B, D, E, H, I, J, F
Depth of a nodeedges from the root down to the nodedepth of E = 2 (A → B → E)
Height of a nodeedges on the longest path from the node down to a leafheight of E = 2 (E → I → J; E → H is shorter, so it does not count)
Height of the treethe height of the root4 (A → B → E → I → J)
Depth of the treethe depth of its deepest node: the same number as the height of the tree4 (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

ABDEHIJFCGKLM12

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

ABDEHIJFCGKLM12shorter:not countedlonger, butnot below E

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 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

3050root

30 is in the left slot.
root.left is 30, root.right is null.

Tree 2

3050root

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 made from a class, with one value and two child references. Compare it with : 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.

TreeNode: the blueprintdataleftright

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.

Step 1 of 7
 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

1020datanextone link: forward

Binary-tree node

503070dataleftrighttwo links: both point down
Singly linked listBinary tree
head refers to the first noderoot refers to the top node
next: one linkleft and right: two links
null: no next nodenull: 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.

8root

Make a node holding 8. The variable root refers to it. Its left and right are null (the small dashed boxes).

Step 1 of 4
 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
30405070

40 is the right child of 30. 30 has no left child (null).

Same values, different shapes

10203040506070

height 2

10203040506070

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:

LevelMost nodes on this levelMost nodes in a tree of this height
011
121 + 2 = 3
243 + 4 = 7
387 + 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

    BKLMQRST
    1. Root?
    2. Leaves?
    3. Parent of R?
    4. Sibling of B?
    5. Ancestors of S?
    6. Depth of L?
    7. Height of T?
    8. Size? Edges?
    9. Is this a binary tree? Why?
    Show the answers
    1. M
    2. B, L, Q, S
    3. T
    4. L
    5. R, T, M
    6. 2
    7. 2 (T → R → Q)
    8. 8 nodes, 7 edges
    9. 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.

    203040507080
    Build this tree. 70 has no left child.

    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.

    1. Which node has no parent?

    2. A node with no children is called:

    3. In the explorer tree, what is the depth of E?

    4. In the explorer tree, what is the height of E?

    5. A tree has 12 nodes. How many edges does it have?

    6. Which statement about a binary tree is true?

    7. In Java, what does root.left.right refer to?

    8. Are left and right like previous and next in a linked list?

    Score: 0 / 8

    Key takeaways

    1. A binary-tree node holds data, a left reference, and a right reference.
    2. The root is the top node. A leaf has no children.
    3. Depth: edges from the root to the node. Height: edges from the node down to its deepest leaf.
    4. A binary tree: every node has at most 2 children.
    5. A missing child is null.

    Next lesson: Binary search trees and BST search.

    References

    1. Programiz, "Tree Data Structure" and "Binary Tree." programiz.com/dsa/trees
    2. N. Dale, D. T. Joyce, and C. Weems, Object-Oriented Data Structures Using Java, 4th ed. Jones & Bartlett Learning, 2018.
    3. mycodeschool, "Data structures: Introduction to trees" and "Binary tree" [Videos], YouTube.