Floor register: Even-key census
Stuck or curious how this works? Visualize Breadth-First Search (BFS) ↗
Inputs
root is the top node of a binary tree. Examples list nodes one level at a time, from left to right. null marks a missing child; [] means no tree. Each node stores its number in val. Its left and right links point to children. The runner builds the nodes for you.
Your tasks
- Create a list
levelSums.rootis the top node of a binary tree. Each node has a value and up to two children. Therootis at depth 0, its children are at depth 1, and so on. Add the values at each depth. Put one sum per depth inlevelSums, starting at depth 0. Missing children add nothing. An empty tree gives an emptylevelSums. - Count the even numbers in
levelSums. Store the count inevenCount. A number is even when it divides by 2 with no remainder. - Complete
floorRegisterEvenKeyCensusso it returnsevenCount. Return it, do not print it.
Example
If root is [12, null, -3, 4, 3], then levelSums is [12, -3, 7] and floorRegisterEvenKeyCensus returns 1.
Rules
- 0 and negative even numbers count too.
- If
levelSumsis empty, return 0.
Test data
TEST DATA 1: root is [18, null, -6, 10, 0].
TEST DATA 2: root is [2, null, 2, 2, -3].
Examples
Input: root = [18,null,-6,10,0] Output: 3
levelSums is [18, -6, 10]. The even numbers are [18, -6, 10]. There are 3, so return 3.
Input: root = [2,null,2,2,-3] Output: 2
levelSums is [2, 2, -1]. The even numbers are [2, 2]. There are 2, so return 2.
Input: root = [] Output: 0
levelSums is []. The even numbers are []. There are 0, so return 0.
Input limits
- 0 <= node count <= 31; null marks a missing child and does not count as a node.
- Answers fit in a signed 32-bit integer: -2,147,483,648 through 2,147,483,647.
- Input numbers have no decimal part. They range from -1,000,000 to 1,000,000. Follow any extra input rules in task 1.
- Linked lists do not loop back to an earlier node. Tree examples list nodes by level; null means a missing child. The runner builds the nodes shown in the examples.
Efficiency goal
Big-O describes how the work or memory needed grows as the input gets larger.
Efficiency goal: time O(n); extra memory, including the helper list, O(n). n is the number of nodes. These labels describe how work and memory grow with the input.
Practice focus
Build levelSums first, then return exactly what the tasks ask for. Follow the order, keep repeated values when the rule says so, and check the empty case.