Problem 255
Count Nodes in a Binary Tree
Easy · 10 pts · Tree, Binary Tree, Depth-First Search
Problem
You are given a binary tree. Print the total number of nodes it contains. The count for a tree is 1 (the root) plus the counts of its left and right subtrees, which gives a one-line recursive solution. A breadth-first walk with a queue that counts every node it visits works equally well and avoids deep recursion for very unbalanced trees.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child.
Output
Print the number of nodes.
Constraints
1 <= number of nodes <= 50000; -1000 <= value <= 1000
Example input
6 1 2 3 4 5 6
Example output
6
Explanation
The tree has root 1, children 2 and 3, and 4, 5 and 6 on the next level. That is 1 + 2 + 3 = 6 nodes.