1. Home
  2. Explore
  3. Computer Science
  4. Introduction to Trees

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Introduction to Trees

Data Structures: Trees (Binary Tree)

Introduction to Trees

A tree is a non-linear data structure in which a node can be connected to multiple other nodes. Unlike linked lists — which are linear — trees allow branching, similar to a family tree where one ancestor can have multiple descendants.


Example of a hierarchical tree structure with a root, branches, and leaves.


Basic Terminologies

Every tree uses a set of standard terms to describe relationships between nodes.

  • Node – Each element in a tree that stores data.

  • Root – The topmost node from which the tree originates. There is exactly one root.

  • Child – A node directly connected to another node when moving away from the root.

  • Parent – The node connected to a child from above (closer to the root).

  • Sibling – Nodes that share the same parent.

  • Ancestor – Any node on the path from the root to a given node (excluding the node itself).

  • Descendant – Any node that lies below a given node in the tree.

  • Leaf – A node with no children (degree 0).

Key takeaway: A tree is a non-linear data structure where nodes are connected in a hierarchical fashion, and each node can have zero or more children.


Binary Tree

A binary tree is a special type of tree where every node has at most two children — typically referred to as the left child and the right child. A node may have 0, 1, or 2 children.

Node structure in a binary tree:

  • data (integer, character, etc.)

  • left – pointer to the left child

  • right – pointer to the right child

If a node has no left or right child, the corresponding pointer is set to NULL (or nullptr).

For trees that allow more than two children (arbitrary number), they are called n-ary trees. In an n-ary tree, the node stores a list of child pointers instead of fixed left/right pointers.


Building a Binary Tree Using Recursion

The most common way to construct a binary tree is through recursion, where the user provides data and uses -1 to indicate a NULL child.

Algorithm (function buildTree()):

  1. Ask the user to enter data for the current node.

  2. If data == -1, return NULL.

  3. Create a new node with the given data.

  4. Recursively build the left subtree: root->left = buildTree().

  5. Recursively build the right subtree: root->right = buildTree().

  6. Return the root node.

Example C++ implementation:

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int d) {
        this->data = d;
        this->left = NULL;
        this->right = NULL;
    }
};

Node* buildTree(Node* root) {
    int data;
    cout << "Enter data: ";
    cin >> data;
    if (data == -1) return NULL;

    root = new Node(data);
    cout << "Enter data for left of " << data << ": ";
    root->left = buildTree(root->left);
    cout << "Enter data for right of " << data << ": ";
    root->right = buildTree(root->right);

    return root;
}

How the recursion works (dry run with input 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1):

  • Root node 1 is created.

  • Recursively builds left subtree: node 3 → its left child 7 (leaf, both children -1) → its right child 11 (leaf).

  • Returns to root, then builds right subtree: node 5 → its left child 17 (leaf) → right child -1 (NULL).

  • Each leaf returns NULL and the full tree is assembled.

Note: The recursion follows a depth-first pattern — it goes completely down the left side before returning to process the right side.


Traversals

Traversal means visiting every node in the tree exactly once. Four fundamental traversals for binary trees are discussed.

Level Order Traversal (Breadth-First)

Nodes are visited level by level, from left to right. For the tree:

        1
       / \
      3   5
     / \  /
    7  11 17

The level order output is: 1 3 5 7 11 17.

How to implement using a queue:

  1. Push the root node into a queue.

  2. While the queue is not empty:

    • Pop the front node (temp).

    • Print temp->data.

    • If temp->left exists, push it.

    • If temp->right exists, push it.

Including level separators (printing levels on separate lines):

To visually separate levels, push a NULL marker after the root and after each completed level.

void levelOrderTraversal(Node* root) {
    queue<Node*> q;
    q.push(root);
    q.push(NULL);            // marker for end of level 0

    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();

        if (temp == NULL) {
            cout << endl;    // finished current level
            if (!q.empty()) {
                q.push(NULL); // marker for next level
            }
        } else {
            cout << temp->data << " ";
            if (temp->left)  q.push(temp->left);
            if (temp->right) q.push(temp->right);
        }
    }
}
  • The null marker acts as a separator. When a NULL is encountered at the front, it means the previous level is fully printed. A newline is inserted.

  • If there are still nodes in the queue, push another NULL to mark the beginning of the next level.

Reverse Level Order Traversal (homework): Visit nodes from the bottommost level upward, left to right within each level. This can be achieved by using a stack or by first performing level order and then reversing the result.

Inorder Traversal (LNR)

Rule: Left → Node → Right

  • Recursively traverse the left subtree.

  • Visit (print) the current node.

  • Recursively traverse the right subtree.

For the example tree, inorder output: 7 3 11 1 17 5

Code:

void inorder(Node* root) {
    if (root == NULL) return;
    inorder(root->left);     // L
    cout << root->data << " "; // N
    inorder(root->right);    // R
}

Preorder Traversal (NLR)

Rule: Node → Left → Right

  • Visit the current node first.

  • Recursively traverse the left subtree.

  • Recursively traverse the right subtree.

For the example tree, preorder output: 1 3 7 11 5 17

Code:

void preorder(Node* root) {
    if (root == NULL) return;
    cout << root->data << " "; // N
    preorder(root->left);      // L
    preorder(root->right);     // R
}

Postorder Traversal (LRN)

Rule: Left → Right → Node

  • Recursively traverse the left subtree.

  • Recursively traverse the right subtree.

  • Visit the current node last.

For the example tree, postorder output: 7 11 3 17 5 1

Code:

void postorder(Node* root) {
    if (root == NULL) return;
    postorder(root->left);     // L
    postorder(root->right);    // R
    cout << root->data << " "; // N
}

Visualising the recursion flow for each traversal:

  • Inorder: always print after left returns, before going right.

  • Preorder: print before any recursion.

  • Postorder: print after both left and right return.

Important: The letters L, N, R guide the entire traversal logic. L = go left, R = go right, N = print current node.


Building a Binary Tree from Level Order Input

Instead of building recursively, the tree can also be constructed by taking level order data (including -1 for NULL nodes). This uses a queue to assign left and right children sequentially.

Algorithm (buildFromLevelOrder):

  1. Read the root's data. If it is -1, set root to NULL and return.

  2. Create the root node and push it into a queue.

  3. While the queue is not empty:

    • Pop the front node (temp).

    • Read data for the left child of temp.

      • If data != -1, create a new node, attach it as temp->left, and push it.

    • Read data for the right child of temp.

      • If data != -1, create a new node, attach it as temp->right, and push it.

  4. The tree is complete.

Implementation:

void buildFromLevelOrder(Node* &root) {
    queue<Node*> q;
    int data;
    cout << "Enter data for root: ";
    cin >> data;
    if (data == -1) {
        root = NULL;
        return;
    }
    root = new Node(data);
    q.push(root);

    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();

        int leftData, rightData;
        cout << "Enter left child of " << temp->data << ": ";
        cin >> leftData;
        if (leftData != -1) {
            temp->left = new Node(leftData);
            q.push(temp->left);
        }

        cout << "Enter right child of " << temp->data << ": ";
        cin >> rightData;
        if (rightData != -1) {
            temp->right = new Node(rightData);
            q.push(temp->right);
        }
    }
}

Input format: The user supplies data level by level, and for each node, the left and right children (or -1) are given in order. The queue ensures that children are attached correctly.


Counting Leaf Nodes (Example Question)

Problem: Given a binary tree, count the number of leaf nodes (nodes with no children).

Approach: Traverse the entire tree using any traversal (e.g., inorder). For each node, if both left and right are NULL, increment a counter.

Code (using inorder):

void countLeaves(Node* root, int &cnt) {
    if (root == NULL) return;
    countLeaves(root->left, cnt);
    if (root->left == NULL && root->right == NULL) {
        cnt++;
    }
    countLeaves(root->right, cnt);
}

// Example usage:
// int cnt = 0;
// countLeaves(root, cnt);
// cout << cnt;  // prints number of leaf nodes

Complexity:

  • Time: O(n)O(n)O(n) — each node is visited exactly once.

  • Space: O(h)O(h)O(h) due to recursion stack, where hhh is the height of the tree (balanced → O(log⁡n)O(\log n)O(logn), skewed → O(n)O(n)O(n)).

The counter is passed by reference to preserve the count across recursive calls.


Important Notes & Homework

  • The four traversals learned:

    • Level Order (with and without separators)

    • Inorder

    • Preorder

    • Postorder

  • Homework tasks:

    1. Implement reverse level order traversal (bottom-to-top, left-to-right).

    2. Write iterative versions of inorder, preorder, and postorder traversals (without recursion) — these will help in understanding stack-based tree algorithms.


Summary: A binary tree is a non-linear data structure with nodes containing data and left/right pointers. Trees can be built recursively (depth-first) or via level order input (breadth-first). The three depth-first traversals (inorder, preorder, postorder) and the breadth-first level order traversal are fundamental for solving tree problems. Counting leaf nodes demonstrates how to apply a traversal to gather information about the tree structure.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent