📖 Scenario: You are working with a simple family tree where each person can have up to two children. You want to find out how many people are in the family tree in total.
🎯 Goal: Build a program that creates a binary tree representing the family, then counts and prints the total number of nodes (people) in the tree.
📋 What You'll Learn
Create a binary tree with exactly 5 nodes using the TreeNode class
Add a helper variable to hold the root node of the tree
Write a recursive method called CountNodes that counts all nodes in the tree
Print the total number of nodes in the tree
💡 Why This Matters
🌍 Real World
Counting nodes in a binary tree is useful in many areas like family trees, decision trees, and file system structures.
💼 Career
Understanding tree structures and recursion is important for software developers working with data organization, search algorithms, and hierarchical data.
Progress0 / 4 steps
1
Create the TreeNode class and build the binary tree
Create a class called TreeNode with an int field called Value and two TreeNode fields called Left and Right. Then create 5 nodes with values 1, 2, 3, 4, and 5. Connect them to form this tree:
1 / \ 2 3 / \ 4 5
DSA C#
Hint
Start by defining the TreeNode class with a constructor. Then create each node and link them as left and right children to form the tree.
2
Create a root variable for the tree
Create a variable called root and set it to node1, which is the root of the tree.
DSA C#
Hint
Just create a new variable called root and assign it the value node1.
3
Write the CountNodes method to count all nodes
Write a recursive method called CountNodes that takes a TreeNode parameter called node and returns an int. It should return 0 if node is null. Otherwise, it should return 1 plus the count of nodes in the left subtree plus the count of nodes in the right subtree.
DSA C#
Hint
Use a simple recursive method that returns 0 if the node is null. Otherwise, add 1 plus the counts from left and right children.
4
Print the total number of nodes in the tree
Write a Console.WriteLine statement to print the result of calling CountNodes with root as the argument.
DSA C#
Hint
Call CountNodes(root) inside Console.WriteLine to print the total count.
Practice
(1/5)
1. What does the function to count total nodes in a binary tree do?
easy
A. Counts only the leaf nodes
B. Counts nodes only on the left subtree
C. Counts only the root node
D. Counts all nodes including root, left, and right children
Solution
Step 1: Understand the node counting concept
The function counts every node in the tree, including root and all children.
Step 2: Differentiate from partial counts
Counting only leaves or root ignores other nodes, so total count includes all nodes.
Final Answer:
Counts all nodes including root, left, and right children -> Option D
Quick Check:
Total nodes = all nodes in tree [OK]
Hint: Count every node visited in tree traversal [OK]
Common Mistakes:
Counting only leaf nodes
Ignoring root node
Counting only one subtree
2. Which of the following is the correct C# syntax to define a binary tree node class for counting nodes?
easy
A. public class Node { public int data; public Node left, right; }
B. class Node { int data; Node left, right; void count() {} }
C. public struct Node { int data; Node left; Node right; }
D. class Node { public int data; public Node left; private Node right; }
Solution
Step 1: Check class and member access
public class Node { public int data; public Node left, right; } correctly defines a public class with public members for data and child nodes.
Step 2: Verify syntax correctness
class Node { int data; Node left, right; void count() {} } misses access modifiers and method is irrelevant; C uses struct which is less common; D has private right node which restricts access.
Final Answer:
public class Node { public int data; public Node left, right; } -> Option A
Quick Check:
Correct class with public members [OK]
Hint: Use public class with public node references [OK]
Common Mistakes:
Missing public keyword
Using struct instead of class
Private child nodes blocking access
3. What is the output of the following C# code that counts nodes in a binary tree?
class Node {
public int data;
public Node left, right;
public Node(int val) { data = val; left = right = null; }
}
int CountNodes(Node root) {
if (root == null) return 0;
return 1 + CountNodes(root.left) + CountNodes(root.right);
}
// Tree:
// 1
// / \
// 2 3
// /
// 4
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
Console.WriteLine(CountNodes(root));
medium
A. 4
B. 3
C. 5
D. 6
Solution
Step 1: Count nodes in the tree structure
The tree has nodes: 1 (root), 2 (left child), 3 (right child), and 4 (left child of 2), total 4 nodes.
Step 2: Apply recursive count function
CountNodes returns 1 + left subtree count + right subtree count, summing to 4.
Final Answer:
4 -> Option A
Quick Check:
Nodes counted = 4 [OK]
Hint: Add 1 for root plus counts of left and right [OK]
Common Mistakes:
Counting only children, missing root
Miscounting null nodes
Adding extra nodes
4. Identify the error in this C# method to count total nodes in a binary tree:
int CountNodes(Node root) {
if (root == null) return 1;
return CountNodes(root.left) + CountNodes(root.right);
}
medium
A. Returns 1 for null node instead of 0
B. Does not count the current root node
C. All of the above
D. Missing addition of 1 for current node
Solution
Step 1: Check base case return value
Returning 1 for null node is incorrect; it should be 0 because null means no node.
Step 2: Check counting logic for current node
Function does not add 1 for the current root node, so it misses counting it.
Step 3: Combine errors
Both base case and missing addition cause wrong total count.
Final Answer:
All of the above -> Option C
Quick Check:
Base case and counting errors combined [OK]
Hint: Base case returns 0; add 1 for current node [OK]
Common Mistakes:
Returning 1 for null node
Not adding 1 for current node
Ignoring base case correctness
5. Given a binary tree where some nodes have only one child, how would you modify the counting function to count only nodes that have at least one child?
hard
A. Count only leaf nodes
B. Count nodes where left or right child is not null, recursively
C. Count all nodes including leaves
D. Count nodes with both children null
Solution
Step 1: Define condition for counting nodes
We want to count nodes that have at least one child, so check if left or right child is not null.
Step 2: Modify recursive function accordingly
Recursively count nodes where left or right child exists, ignoring leaf nodes with no children.
Step 3: Implement logic
Return 1 + counts of children if node has child; else 0 for leaf nodes.
Final Answer:
Count nodes where left or right child is not null, recursively -> Option B
Quick Check:
Count nodes with children only [OK]
Hint: Count nodes with at least one child only [OK]
Common Mistakes:
Counting all nodes including leaves
Counting only leaves
Counting nodes with no children
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.