Binary Trees (Cambridge (CIE) A Level Computer Science): Revision Note

Exam code: 9618

Robert Hampton

Written by: Robert Hampton

Reviewed by: James Woodhouse

Updated on

Binary trees

What is a binary tree?

  • A binary tree is a rooted tree where every node has a maximum of 2 nodes

  • A binary tree is essentially a graph and therefore can be implemented in the same way

  • You must understand:

    • Tree traversal of a tree data structure

    • Add new data to a tree

    • Remove data from a tree

binary-trees
  • The most common way to represent a binary tree is by storing each node with a left and right pointer

This information is usually implemented using 2D arrays 

binary-trees-2

Tree terminology

Keyword

Definition

Node

An item in a tree

Edge

Connects two nodes together and is also known as a branch or pointer

Root

A single node which does not have any incoming nodes

Child

A node with incoming edges

Parent

A node with outgoing edges

Subtree

A subsection of a tree consisting of a parent and all the children of a parent

Leaf

A node with no children

Traversing

The process of visiting each node in a tree data structure, exactly once

How do you program a tree?

  • In the following example:

    • A tree is represented using a TreeNode structure, which includes:

      • A value field to store the data held in the node

      • A children field to store a collection (e.g. list or array) of child nodes

    • The createTreeNode function is used to initialise a new tree node, setting its value and creating an empty collection for its children

    • The addChild function allows a new child node to be added to a parent node

      • It creates a new TreeNode with the given value and appends it to the parent's children collection

    • Finally, the createTreeNode function is used to create the root node

      • Additional child nodes are added using the addChild function, allowing a multi-level tree structure to be built with branches and sub-branches

Pseudocode

CLASS TreeNode
    DECLARE value : STRING
    DECLARE children : ARRAY OF TreeNode
ENDCLASS

FUNCTION createTreeNode(val : STRING) RETURNS TreeNode
    DECLARE node : TreeNode
    SET node = NEW TreeNode
    SET node.value = val
    SET node.children = []
    RETURN node
ENDFUNCTION

PROCEDURE addChild(parent : TreeNode, childValue : STRING)
    DECLARE childNode : TreeNode
    SET childNode = createTreeNode(childValue)
    APPEND childNode TO parent.children
ENDPROCEDURE

// Example usage
DECLARE root : TreeNode
SET root = createTreeNode("Root")

CALL addChild(root, "Child 1")
CALL addChild(root, "Child 2")

// Adding a grandchild to Child 1
DECLARE child1 : TreeNode
SET child1 = root.children[0]
CALL addChild(child1, "Grandchild 1.1")

Python

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []

def createTreeNode(val):
    return TreeNode(val)

def addChild(parent, childValue):
    childNode = createTreeNode(childValue)
    parent.children.append(childNode)

# Example usage
root = createTreeNode("Root")

addChild(root, "Child 1")
addChild(root, "Child 2")

# Adding a grandchild to "Child 1"
child1 = root.children[0]
addChild(child1, "Grandchild 1.1")

Java

import java.util.ArrayList;

class TreeNode {
    String value;
    ArrayList<TreeNode> children;

    // Constructor
    public TreeNode(String value) {
        this.value = value;
        this.children = new ArrayList<>();
    }
}

public class TreeExample {

    // Function to create a tree node
    public static TreeNode createTreeNode(String val) {
        return new TreeNode(val);
    }

    // Function to add a child to a parent node
    public static void addChild(TreeNode parent, String childValue) {
        TreeNode childNode = createTreeNode(childValue);
        parent.children.add(childNode);
    }

    public static void main(String[] args) {
        // Create the root node
        TreeNode root = createTreeNode("Root");

        // Add children to the root
        addChild(root, "Child 1");
        addChild(root, "Child 2");

        // Add a grandchild to "Child 1"
        TreeNode child1 = root.children.get(0);
        addChild(child1, "Grandchild 1.1");
    }
}

Algorithm to traverse a tree structure

Pseudocode - pre-order tree traversal

PROCEDURE traverseTree(node : TreeNode)
    IF node = NULL THEN
        RETURN
    ENDIF

    OUTPUT node.value

    FOR EACH child IN node.children DO
        CALL traverseTree(child)
    NEXT
ENDPROCEDURE

// Call the traversal on the root
CALL traverseTree(root)

Python - pre-order tree traversal

def traverseTree(node):
    if node is None:
        return

    print(node.value)

    for child in node.children:
        traverseTree(child)

# Call the traversal
traverseTree(root)

Java - pre-order tree traversal

public static void traverseTree(TreeNode node) {
    if (node == null) {
        return;
    }

    System.out.println(node.value);

    for (TreeNode child : node.children) {
        traverseTree(child);
    }
}

// In main:
traverseTree(root);
  • For a tree like:

    Root

    ├── Child 1

    │ └── Grandchild 1.1

    └── Child 2

  • The output will be:

    Root

    Child 1

    Grandchild 1.1

    Child 2

Algorithm to add data to a tree structure

Pseudocode

PROCEDURE addChild(parent : TreeNode, childValue : STRING)
    DECLARE childNode : TreeNode
    SET childNode = createTreeNode(childValue)
    APPEND childNode TO parent.children
ENDPROCEDURE

// Usage:
CALL addChild(root, "New Child")

Python

def addChild(parent, childValue):
    childNode = TreeNode(childValue)
    parent.children.append(childNode)

# Usage:
addChild(root, "New Child")

Java

public static void addChild(TreeNode parent, String childValue) {
    TreeNode childNode = new TreeNode(childValue);
    parent.children.add(childNode);
}

// Usage in main:
addChild(root, "New Child");
  • These examples all create a new node with the provided value and attach it to the given parent node

  • This approach allows dynamic construction of trees with multiple levels

Algorithm to remove data to a tree structure

Pseudocode

PROCEDURE removeChild(parent : TreeNode, targetValue : STRING)
    FOR index FROM 0 TO LENGTH(parent.children) - 1
        IF parent.children[index].value = targetValue THEN
            REMOVE parent.children[index]
            RETURN
        ENDIF
    NEXT
ENDPROCEDURE

// Usage
CALL removeChild(root, "Child 1")

Python

def removeChild(parent, targetValue):
    for i in range(len(parent.children)):
        if parent.children[i].value == targetValue:
            del parent.children[i]
            return  # Exit after removing first match

# Usage:
removeChild(root, "Child 1")

Java

public static void removeChild(TreeNode parent, String targetValue) {
    for (int i = 0; i < parent.children.size(); i++) {
        if (parent.children.get(i).value.equals(targetValue)) {
            parent.children.remove(i);
            return; // Exit after first match
        }
    }
}

// Usage in main:
removeChild(root, "Child 1");
  • This only removes the first matching child from the direct children of a node

  • If you want to remove nodes anywhere in the tree, you’d need a recursive version

  • REMOVE and del and .remove() work because the children collection is a list/array

👀 You've read 1 of your 5 free revision notes this week
An illustration of students holding their exam resultsUnlock more revision notes. It’s free!

By signing up you agree to our Terms and Privacy Policy.

Already have an account? Log in

Did this page help you?

Robert Hampton

Author: Robert Hampton

Expertise: Computer Science Content Creator

Rob has over 16 years' experience teaching Computer Science and ICT at KS3 & GCSE levels. Rob has demonstrated strong leadership as Head of Department since 2012 and previously supported teacher development as a Specialist Leader of Education, empowering departments to excel in Computer Science. Beyond his tech expertise, Robert embraces the virtual world as an avid gamer, conquering digital battlefields when he's not coding.

James Woodhouse

Reviewer: James Woodhouse

Expertise: Computer Science & English Subject Lead

James graduated from the University of Sunderland with a degree in ICT and Computing education. He has over 14 years of experience both teaching and leading in Computer Science, specialising in teaching GCSE and A-level. James has held various leadership roles, including Head of Computer Science and coordinator positions for Key Stage 3 and Key Stage 4. James has a keen interest in networking security and technologies aimed at preventing security breaches.

Download notes on Binary Trees