ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Recursive Binary Search Tree Node Count

TSX

Goal -- WPM

Ready
Exercise Algorithm Area
1interface TreeNode {
2value: number;
3left: TreeNode | null;
4right: TreeNode | null;
5}
6
7function countNodes(root: TreeNode | null): number {
8if (root === null) {
9return 0;
10}
11return 1 + countNodes(root.left) + countNodes(root.right);
12}
Algorithm description viewbox

Recursive Binary Search Tree Node Count

Algorithm description:

This function recursively counts the total number of nodes in a Binary Search Tree (BST). It's a fundamental operation for understanding tree structures and is often a prerequisite for other tree-based algorithms, like calculating height or finding the median.

Algorithm explanation:

The `countNodes` function leverages recursion to traverse a Binary Search Tree. The base case is when `root` is `null`, indicating an empty subtree, in which case it returns 0. Otherwise, it returns 1 (for the current node) plus the count of nodes in its left subtree and the count of nodes in its right subtree. This process effectively visits every node exactly once. The time complexity is O(n), where n is the number of nodes, as each node is processed. The space complexity is O(h) in the average case (balanced tree) and O(n) in the worst case (skewed tree) due to the recursion call stack, where h is the height of the tree.

Pseudocode:

function countNodes(node):
  if node is null:
    return 0
  return 1 + countNodes(node.left) + countNodes(node.right)