π§ Intuition
When you're at any node:
- Count yourself β thatβs
1 - Count everything in your left subtree
- Count everything in your right subtree
So, the total nodes at any point =
π 1 + countNodes(left) + countNodes(right)
π¦ Code
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function(root) {
if (root === null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
};
π Step-by-Step with Example Tree
Letβs say this is our tree:
1
/ \
2 3
/
4
- Node 1 has two children
- Node 2 has one child (node 4)
- Node 3 has no children
- Node 4 has no children
π Call Stack Walkthrough
πΉ Step 1: Start from root
countNodes(1)
= 1 + countNodes(2) + countNodes(3)
πΉ Step 2: Go to node 2
countNodes(2)
= 1 + countNodes(4) + countNodes(null)
-
countNodes(4)= 1 (itβs a leaf) -
countNodes(null)= 0
So, countNodes(2) = 1 + 1 + 0 = 2
πΉ Step 3: Go to node 3
countNodes(3)
= 1 + countNodes(null) + countNodes(null)
= 1 + 0 + 0 = **1**
πΉ Final Step: Back to root
countNodes(1)
= 1 + 2 (from node 2) + 1 (from node 3)
= 4
β Total nodes = 4
π Visual Call Tree
countNodes(1)
βββ countNodes(2)
β βββ countNodes(4)
β β βββ countNodes(null) β 0
β β βββ countNodes(null) β 0
β βββ countNodes(null) β 0
βββ countNodes(3)
βββ countNodes(null) β 0
βββ countNodes(null) β 0
βοΈ Time Complexity
- Each node is visited once
- So total time is O(n), where n is number of nodes
π― Key Takeaway
This line does everything:
return 1 + countNodes(root.left) + countNodes(root.right);
It says:
β
βI am 1 node, plus whatever is on my left, plus whatever is on my right.β
Top comments (0)