Data Structure Trees Practice Questions with Solutions

Introductions

Trees are non-linear data structures used to represent data in a hierarchical form. A tree contains nodes connected by edges, with one node usually acting as the root. These practice questions focus on actually working with trees rather than only learning definitions. You will practice creating nodes, connecting them, finding parent and child nodes, calculating tree height, counting nodes and leaves, searching values, and performing basic tree traversal. Data Structure Trees practice questions with solutions help to understand the concepts.

Question 1: Create a Simple Tree

Question

Create the following tree using JavaScript:

        10
       /  \
      20   30

Print the root, left child, and right child.

Solution

First, create a node structure:

class Node {
    constructor(value) {
        this.value = value;
        this.children = [];
    }
}

Create three nodes:

let root = new Node(10);
let left = new Node(20);
let right = new Node(30);

Connect 20 and 30 to 10:

root.children.push(left);
root.children.push(right);

Complete code:

class Node {
    constructor(value) {
        this.value = value;
        this.children = [];
    }
}

let root = new Node(10);
let left = new Node(20);
let right = new Node(30);

root.children.push(left);
root.children.push(right);

console.log("Root:", root.value);
console.log("Left Child:", root.children[0].value);
console.log("Right Child:", root.children[1].value);

The structure is:

        10
       /  \
      20   30

Output

Root: 10
Left Child: 20
Right Child: 30

Answer

10 is the root node, while 20 and 30 are its child nodes.


Question 2: Find the Parent of a Node

Question

Consider this tree:

        10
       /  \
      20   30
     / \
    40  50

Find the parent of node 50.

Solution

From the tree:

        10
       /  \
      20   30
     / \
    40  50

Node 50 is directly connected below node 20.

Therefore:

Parent of 50 = 20

We can represent the tree using objects:

let tree = {
    value: 10,
    children: [
        {
            value: 20,
            children: [
                { value: 40, children: [] },
                { value: 50, children: [] }
            ]
        },
        {
            value: 30,
            children: []
        }
    ]
};

A simple recursive search can find the parent:

function findParent(node, target) {

    for (let child of node.children) {

        if (child.value === target) {
            return node.value;
        }

        let result = findParent(child, target);

        if (result !== null) {
            return result;
        }
    }

    return null;
}

console.log(findParent(tree, 50));

Output

20

Answer

The parent of node 50 is 20.


Question 3: Count the Total Number of Nodes

Question

Count the total number of nodes in this tree:

          10
        /    \
       20     30
      / \      \
     40  50     60

Solution

Let’s count the nodes:

10
20
30
40
50
60

There are 6 nodes.

We can also solve this using recursion.

function countNodes(node) {

    if (node === null) {
        return 0;
    }

    let count = 1;

    for (let child of node.children) {
        count += countNodes(child);
    }

    return count;
}

Create the tree:

let tree = {
    value: 10,
    children: [
        {
            value: 20,
            children: [
                { value: 40, children: [] },
                { value: 50, children: [] }
            ]
        },
        {
            value: 30,
            children: [
                { value: 60, children: [] }
            ]
        }
    ]
};

console.log(countNodes(tree));

The function counts the current node and then recursively counts every child.

Output

6

Answer

The tree contains 6 nodes.


Question 4: Count the Leaf Nodes

Question

Find the number of leaf nodes in this tree:

          10
        /    \
       20     30
      / \      \
     40  50     60

Solution

A leaf node is a node that has no children.

In this tree:

40 → Leaf
50 → Leaf
60 → Leaf

Therefore, there are 3 leaf nodes.

We can solve it programmatically:

function countLeaves(node) {

    if (node.children.length === 0) {
        return 1;
    }

    let count = 0;

    for (let child of node.children) {
        count += countLeaves(child);
    }

    return count;
}

let tree = {
    value: 10,
    children: [
        {
            value: 20,
            children: [
                { value: 40, children: [] },
                { value: 50, children: [] }
            ]
        },
        {
            value: 30,
            children: [
                { value: 60, children: [] }
            ]
        }
    ]
};

console.log(countLeaves(tree));

Output

3

Answer

The tree has 3 leaf nodes: 40, 50, and 60.


Question 5: Find the Height of a Tree

Question

Find the height of this tree:

          10
        /    \
       20     30
      / \
     40  50

Consider the height as the number of edges on the longest path from the root to a leaf.

Solution

The longest path is:

10 → 20 → 40

There are two edges:

10 → 20     = 1 edge
20 → 40     = 2 edges

Therefore:

Height = 2

Recursive solution:

function height(node) {

    if (node.children.length === 0) {
        return 0;
    }

    let maxHeight = 0;

    for (let child of node.children) {
        maxHeight = Math.max(maxHeight, height(child));
    }

    return maxHeight + 1;
}

Tree:

let tree = {
    value: 10,
    children: [
        {
            value: 20,
            children: [
                { value: 40, children: [] },
                { value: 50, children: [] }
            ]
        },
        {
            value: 30,
            children: []
        }
    ]
};

console.log(height(tree));

Output

2

Answer

The height of the tree is 2 edges.

Note: Some resources define tree height using the number of nodes on the longest path instead of edges. Always check which definition a question uses.


Question 6: Search for a Value in a Tree

Question

Search for the value 50 in this tree:

          10
        /    \
       20     30
      / \      \
     40  50     60

Return true if the value exists and false otherwise.

Solution

We can recursively check every node.

function search(node, target) {

    if (node.value === target) {
        return true;
    }

    for (let child of node.children) {

        if (search(child, target)) {
            return true;
        }
    }

    return false;
}

Create the tree:

let tree = {
    value: 10,
    children: [
        {
            value: 20,
            children: [
                { value: 40, children: [] },
                { value: 50, children: [] }
            ]
        },
        {
            value: 30,
            children: [
                { value: 60, children: [] }
            ]
        }
    ]
};

console.log(search(tree, 50));

The search checks:

10 → Not found
20 → Not found
40 → Not found
50 → Found

Output

true

Answer

The value 50 exists in the tree.


Question 7: Find the Number of Children of a Node

Question

Given:

          10
        /    \
       20     30
      / | \
     40 50 60

Find the number of children of node 20.

Solution

Node 20 has these direct children:

40
50
60

Therefore:

Number of children = 3

Using JavaScript:

let tree = {
    value: 10,
    children: [
        {
            value: 20,
            children: [
                { value: 40, children: [] },
                { value: 50, children: [] },
                { value: 60, children: [] }
            ]
        },
        {
            value: 30,
            children: []
        }
    ]
};

console.log(tree.children[0].children.length);

Output

3

Answer

Node 20 has 3 direct children.


Question 8: Perform Preorder Traversal

Question

Perform a preorder traversal of this tree:

          10
        /    \
       20     30
      / \      \
     40  50     60

Solution

In preorder traversal, we process:

Root → Children

For this tree:

10
├── 20
│   ├── 40
│   └── 50
└── 30
    └── 60

The traversal order is:

10 → 20 → 40 → 50 → 30 → 60

Recursive code:

function preorder(node) {

    console.log(node.value);

    for (let child of node.children) {
        preorder(child);
    }
}

let tree = {
    value: 10,
    children: [
        {
            value: 20,
            children: [
                { value: 40, children: [] },
                { value: 50, children: [] }
            ]
        },
        {
            value: 30,
            children: [
                { value: 60, children: [] }
            ]
        }
    ]
};

preorder(tree);

Output

10
20
40
50
30
60

Answer

The preorder traversal is:

10 → 20 → 40 → 50 → 30 → 60

Question 9: Find the Level of a Node

Question

Find the level of node 50 in this tree:

          10
        /    \
       20     30
      / \
     40  50

Consider the root as level 0.

Solution

Start at the root:

10 → Level 0

Its children:

20 → Level 1
30 → Level 1

Children of 20:

40 → Level 2
50 → Level 2

Therefore:

Level of 50 = 2

We can find the level recursively:

function findLevel(node, target, level) {

    if (node.value === target) {
        return level;
    }

    for (let child of node.children) {

        let result = findLevel(child, target, level + 1);

        if (result !== -1) {
            return result;
        }
    }

    return -1;
}

let tree = {
    value: 10,
    children: [
        {
            value: 20,
            children: [
                { value: 40, children: [] },
                { value: 50, children: [] }
            ]
        },
        {
            value: 30,
            children: []
        }
    ]
};

console.log(findLevel(tree, 50, 0));

Output

2

Answer

Node 50 is at level 2 when the root is considered level 0.


Question 10: Find the Sum of All Nodes

Question

Find the sum of all nodes in this tree:

          10
        /    \
       20     30
      / \      \
     40  50     60

Solution

First list all values:

10 + 20 + 30 + 40 + 50 + 60

Calculate:

10 + 20 = 30
30 + 30 = 60
60 + 40 = 100
100 + 50 = 150
150 + 60 = 210

So the answer is 210.

We can also solve it recursively:

function sumNodes(node) {

    let sum = node.value;

    for (let child of node.children) {
        sum += sumNodes(child);
    }

    return sum;
}

let tree = {
    value: 10,
    children: [
        {
            value: 20,
            children: [
                { value: 40, children: [] },
                { value: 50, children: [] }
            ]
        },
        {
            value: 30,
            children: [
                { value: 60, children: [] }
            ]
        }
    ]
};

console.log(sumNodes(tree));

Output

210

Answer

The sum of all nodes is 210.

Key Takeaways

  • A tree is a non-linear data structure used to represent hierarchical data.
  • The topmost node is called the root.
  • Nodes directly connected below another node are its children.
  • The node directly above another node is its parent.
  • A node without children is called a leaf node.
  • The number of edges on the longest path from the root to a leaf can be used to define tree height.
  • A node’s level represents its distance from the root when the root is assigned a specific starting level.
  • Trees can contain many levels of nodes.
  • Recursion is commonly used to process tree structures.
  • Tree traversal means visiting the nodes of a tree in a particular order.
  • Preorder traversal visits the current node before its children.
  • Searching, counting nodes, finding height, and calculating sums are common tree problems.
  • The basic tree concepts introduced here are useful before learning specialized trees such as Binary Trees, Binary Search Trees, AVL Trees, and Heaps.

FAQs

1. What is a tree in data structures?

A tree is a non-linear data structure that organizes data in a hierarchical relationship using nodes and edges.

2. What is the root node of a tree?

The root is the topmost node of a tree. It does not have a parent node.

3. What is a leaf node?

A leaf node is a node that does not have any children.

4. What is the difference between a parent and a child node?

A parent node is directly above another node, while the node directly connected below it is called its child.

5. What is tree traversal?

Tree traversal is the process of visiting the nodes of a tree in a particular order. Examples include preorder, inorder, postorder, and level-order traversal.

6. Why is recursion commonly used with trees?

Trees naturally contain smaller tree structures inside them. Recursion makes it convenient to process each node and its child subtrees.

7. What is the difference between tree height and tree level?

The level describes how far a particular node is from the root, while height describes the longest downward path from a node to a leaf. The exact counting convention can vary, so the definition used in the question should always be checked.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top