Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Count Nodes in Binary Tree

Medium Acceptance 64.00% Points 30.00

Given the root of a binary tree, return the total number of nodes in the tree.

Each node in the tree contains a value and may have a left child, a right child, or both. The task is to count all nodes present in the tree, including the root.

Examples
Example 1

Example 1

Input: root = [1,2,3,4,5,6]

Output: 6

Explanation: The tree contains six nodes: 1, 2, 3, 4, 5, and 6. Therefore, the total node count is 6.

Example 2

Example 2

Input: root = [1,null,2]

Output: 2

Explanation: The tree has two nodes: 1 and 2. Hence, the total count is 2.

Example 3

Example 3

Input: root = []

Output: 0

Explanation: If the tree is empty, there are no nodes, so the count is 0.

Hints
Hint 1
N/A
Constraints
  • 0 = number of nodes = 105
  • -104 = Node.val = 104
Companies
Microsoft Apple
Topics
Recursion
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions