Bird
Raised Fist0
DSA Javaprogramming~20 mins

Count Total Nodes in Binary Tree in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Binary Tree Node Counting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of counting nodes in this binary tree?
Given the following Java code that counts total nodes in a binary tree, what will be the output printed?
DSA Java
class Node {
    int data;
    Node left, right;
    Node(int data) {
        this.data = data;
        left = right = null;
    }
}

public class BinaryTree {
    Node root;

    int countNodes(Node node) {
        if (node == null) return 0;
        return 1 + countNodes(node.left) + countNodes(node.right);
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(10);
        tree.root.left = new Node(20);
        tree.root.right = new Node(30);
        tree.root.left.left = new Node(40);
        tree.root.left.right = new Node(50);
        System.out.println(tree.countNodes(tree.root));
    }
}
A6
B4
C3
D5
Attempts:
2 left
💡 Hint
Count each node starting from root, including all children.
❓ Predict Output
intermediate
2:00remaining
What is the output after adding one more node?
If we add one more node as the right child of node 30 in the previous tree, what will be the output of countNodes?
DSA Java
class Node {
    int data;
    Node left, right;
    Node(int data) {
        this.data = data;
        left = right = null;
    }
}

public class BinaryTree {
    Node root;

    int countNodes(Node node) {
        if (node == null) return 0;
        return 1 + countNodes(node.left) + countNodes(node.right);
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(10);
        tree.root.left = new Node(20);
        tree.root.right = new Node(30);
        tree.root.left.left = new Node(40);
        tree.root.left.right = new Node(50);
        tree.root.right.right = new Node(60);
        System.out.println(tree.countNodes(tree.root));
    }
}
A6
B5
C7
D4
Attempts:
2 left
💡 Hint
Count all nodes including the new one added.
🧠 Conceptual
advanced
1:30remaining
Why does the countNodes method use recursion?
Why is recursion a good choice to count total nodes in a binary tree?
ABecause recursion automatically sorts the nodes while counting.
BBecause recursion uses less memory than iteration in trees.
CBecause recursion naturally visits each node and its children in a simple way.
DBecause recursion avoids visiting nodes multiple times by caching results.
Attempts:
2 left
💡 Hint
Think about how trees have branches and recursion follows branches easily.
🔧 Debug
advanced
2:00remaining
What error occurs in this code?
What error will this code produce when counting nodes?
DSA Java
class Node {
    int data;
    Node left, right;
    Node(int data) {
        this.data = data;
        left = right = null;
    }
}

public class BinaryTree {
    Node root;

    int countNodes(Node node) {
        if (node == null) return 0;
        return 1 + countNodes(node.left) + countNodes(node.right);
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(10);
        tree.root.left = new Node(20);
        tree.root.right = new Node(30);
        tree.root.left.left = new Node(40);
        tree.root.left.right = new Node(50);
        tree.root.left.left.left = tree.root; // creates cycle
        System.out.println(tree.countNodes(tree.root));
    }
}
AStackOverflowError due to infinite recursion
BNullPointerException when accessing left child
CCompilation error due to invalid assignment
DPrints 5 without error
Attempts:
2 left
💡 Hint
Think about what happens if a node points back to an ancestor.
🚀 Application
expert
3:00remaining
How to modify countNodes to avoid infinite recursion in cyclic trees?
Given a binary tree that may contain cycles, how can you modify the countNodes method to avoid infinite recursion and count each node only once?
AIncrease the recursion depth limit to handle cycles.
BUse a Set to track visited nodes and skip counting nodes already visited.
CRemove all left child references before counting nodes.
DCount nodes only up to a fixed depth to prevent infinite loops.
Attempts:
2 left
💡 Hint
Think about remembering which nodes you have already counted.

Practice

(1/5)
1. What does the function to count total nodes in a binary tree do?
easy
A. It counts all nodes including root, left, and right children.
B. It counts only the leaf nodes of the tree.
C. It counts only the nodes on the left subtree.
D. It counts only the nodes on the right subtree.

Solution

  1. Step 1: Understand the node counting function

    The function visits every node in the tree, including root, left, and right children.
  2. Step 2: Summarize the counting process

    It adds 1 for the current node plus counts from left and right subtrees recursively.
  3. Final Answer:

    It counts all nodes including root, left, and right children. -> Option A
  4. Quick Check:

    Total nodes = all nodes in tree [OK]
Hint: Count every node visited including root and children [OK]
Common Mistakes:
  • Counting only leaf nodes
  • Ignoring one subtree
  • Counting nodes twice
2. Which of the following is the correct Java method signature to count total nodes in a binary tree?
easy
A. public int countNodes(TreeNode root)
B. int countNodes()
C. void countNodes(TreeNode root)
D. public static void countNodes(TreeNode root)

Solution

  1. Step 1: Identify method return type and parameters

    The method should return an integer count and accept the root node as parameter.
  2. Step 2: Match correct Java syntax

    public int countNodes(TreeNode root) correctly declares public int countNodes(TreeNode root) which returns count.
  3. Final Answer:

    public int countNodes(TreeNode root) -> Option A
  4. Quick Check:

    Method returns int and takes root node [OK]
Hint: Method returns int and takes root node parameter [OK]
Common Mistakes:
  • Using void return type
  • Missing root parameter
  • Incorrect access modifier
3. What is the output of the following code snippet?
class TreeNode {
  int val;
  TreeNode left, right;
  TreeNode(int val) { this.val = val; }
}

public class Main {
  public static int countNodes(TreeNode root) {
    if (root == null) return 0;
    return 1 + countNodes(root.left) + countNodes(root.right);
  }

  public static void main(String[] args) {
    TreeNode root = new TreeNode(1);
    root.left = new TreeNode(2);
    root.right = new TreeNode(3);
    root.left.left = new TreeNode(4);
    System.out.println(countNodes(root));
  }
}
medium
A. 3
B. 4
C. 5
D. 6

Solution

  1. Step 1: Count nodes in the tree structure

    The tree has nodes: 1 (root), 2 (left), 3 (right), and 4 (left-left child). Total 4 nodes.
  2. Step 2: Apply recursive countNodes function

    Function returns 1 + count of left subtree + count of right subtree = 4.
  3. Final Answer:

    4 -> Option B
  4. Quick Check:

    Nodes counted = 4 [OK]
Hint: Add 1 for root plus counts of left and right subtrees [OK]
Common Mistakes:
  • Forgetting to count root node
  • Miscounting null children
  • Confusing node values with count
4. Find the error in this code to count total nodes in a binary tree:
public int countNodes(TreeNode root) {
  if (root == null) {
    return 1;
  }
  return 1 + countNodes(root.left) + countNodes(root.right);
}
medium
A. Does not count the current node
B. Missing base case for leaf nodes
C. Returns 1 when root is null instead of 0
D. Uses wrong method signature

Solution

  1. Step 1: Check base case for null node

    Function returns 1 when root is null, which is incorrect; it should return 0.
  2. Step 2: Verify counting logic

    The counting logic correctly adds 1 for the current node and recurses to both subtrees.
  3. Final Answer:

    Returns 1 when root is null instead of 0 -> Option C
  4. Quick Check:

    Base case must return 0 for null [OK]
Hint: Base case for null must return 0 nodes [OK]
Common Mistakes:
  • Returning 1 for null node
  • Not adding 1 for current node
  • Incorrect recursion calls
5. Given a binary tree where each node has either 0 or 2 children, and the total nodes count is 15, how many leaf nodes does the tree have?
hard
A. 7
B. 15
C. 16
D. 8

Solution

  1. Step 1: Use property of full binary tree

    In a full binary tree, number of leaf nodes = number of internal nodes + 1.
  2. Step 2: Calculate leaf nodes from total nodes

    Total nodes = leaf nodes + internal nodes = 15. So leaf nodes = internal nodes + 1. Let internal nodes = x, then x + (x + 1) = 15 -> 2x + 1 = 15 -> 2x = 14 -> x = 7. Leaf nodes = 7 + 1 = 8.
  3. Final Answer:

    8 -> Option D
  4. Quick Check:

    Leaf nodes = internal nodes + 1 = 8 [OK]
Hint: In full binary tree, leaves = internal nodes + 1 [OK]
Common Mistakes:
  • Confusing total nodes with leaf nodes
  • Forgetting full binary tree property
  • Incorrect algebra for leaf count
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard