0
0
DSA Typescriptprogramming~30 mins

Count Total Nodes in Binary Tree in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Count Total Nodes in Binary Tree
📖 Scenario: You are working with a simple binary tree structure used in many applications like organizing data or representing decisions. Your task is to count how many nodes are in this tree.
🎯 Goal: Build a TypeScript program that creates a binary tree, sets up a counter, counts all nodes in the tree using a function, and prints the total count.
📋 What You'll Learn
Create a binary tree using the given TreeNode class
Create a variable count to hold the total number of nodes
Write a recursive function countNodes that counts nodes in the tree
Print the total number of nodes using console.log
💡 Why This Matters
🌍 Real World
Counting nodes in a binary tree is useful in many areas like file systems, decision trees, and organizing data hierarchically.
💼 Career
Understanding tree traversal and counting nodes is a fundamental skill for software developers working with data structures, algorithms, and system design.
Progress0 / 4 steps
1
Create the binary tree
Create the binary tree nodes using the TreeNode class exactly as shown: root node with value 1, left child with value 2, and right child with value 3. Assign the root node to a variable called root.
DSA Typescript
Hint

Use the new TreeNode(value, left, right) constructor to create nodes. The root has value 1, left child 2, and right child 3.

2
Create a count variable
Create a variable called count and set it to 0. This will hold the total number of nodes counted.
DSA Typescript
Hint

Use let count = 0; to create the variable.

3
Write the recursive function to count nodes
Write a recursive function called countNodes that takes a TreeNode | null parameter called node. If node is not null, increase count by 1, then call countNodes on node.left and node.right.
DSA Typescript
Hint

Use a function with a base check for null. Increase count by 1 for each node, then call the function on left and right children.

4
Call the function and print the total count
Call the function countNodes with the variable root as argument. Then print the value of count using console.log(count).
DSA Typescript
Hint

Call countNodes(root); then print count with console.log(count);.