Mental Model
We want to find how many nodes are in a tree by visiting each node once and counting it.
Analogy: Imagine counting all the people in a family tree by visiting each person and adding one to your count.
1 / \ 2 3 / 4
1 / \ 2 3 / 4
Visited: 1
Visited: 1 -> 2
Visited: 1 -> 2 -> 4
Back to node 2
Back to node 1
Visited: 1 -> 3
Back to node 1
Final count = 4
1 -> 2 -> 4 -> 3 -> null Total nodes: 4
using System; class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; } } class BinaryTree { public Node root; // Count total nodes in binary tree public int CountNodes(Node node) { if (node == null) return 0; // base case: no node here // count current node + left subtree + right subtree return 1 + CountNodes(node.left) + CountNodes(node.right); } static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); int totalNodes = tree.CountNodes(tree.root); Console.WriteLine("1 -> 2 -> 4 -> 3 -> null"); Console.WriteLine("Total nodes: " + totalNodes); } }
if (node == null)
return 0; // base case: no node herereturn 1 + CountNodes(node.left) + CountNodes(node.right);if (node == null) return 0;
return 1 + CountNodes(node.left) + CountNodes(node.right);
return 1 + CountNodes(node.left) + CountNodes(node.right);
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));int CountNodes(Node root) {
if (root == null) return 1;
return CountNodes(root.left) + CountNodes(root.right);
}Pass the test and this pattern moves unknown