You are given a binary tree. Write a function to find the "sum of all nodes" at even levels. Please write a function that solves this problem, and explain your algorithm.
Assistant
We are given: "You are given a binary tree. Write a function to find the 'sum of all nodes' at even levels. Please write a function that solves this problem, and explain your algorithm."
Interpretation: We have a binary tree. We want the sum of all nodes that are at even levels. Typically, the root is at level 0 (even). Then level 1 is odd, level 2 even, etc. So we sum nodes at levels 0,2,4,... Alternatively, sometimes level numbering starts at 1, but "even levels" could mean levels that are even numbers. But it's ambiguous. However, typical convention: root at level 0 (even) or level 1? The problem statement says "even levels". I think we need to clarify. Many problems define level 0 as root. But sometimes they define level 1 as root. Since it says "even levels", if root is level 1, then level 1 is odd, so even levels would be 2,4,... But that would exclude root. It's possible. However, it's more common in computer science to have root at level 0. But to be safe, we can ask: but we cannot. We'll assume root at level 0 (even). But we can also make it configurable? The problem just says "sum of all nodes at even levels". I'll assume root is at level 0. So we sum nodes at levels 0,2,4,...
Algorithm: We can do a BFS or DFS traversal, keeping track of the current level. For each node, if level is even, add its value to sum. Return sum.
Time complexity: O(n) where n is number of nodes. Space complexity: O(h) for recursion stack or O(width) for BFS.
Implementation: We'll define a TreeNode class (if not given, we assume it's defined). We'll write a function sum_even_level(root) that returns the sum.
We can do iterative BFS:
Initialize queue with (root, level=0). While queue not empty, pop node and level. If level % 2 == 0, add node.val to sum. Then push left and right children with level+1.
Alternatively, DFS recursion:
def dfs(node, level):
if not node: return 0
s = node.val if level % 2 == 0 else 0
return s + dfs(node.left, level+1) + dfs(node.right, level+1)
Then call dfs(root, 0).
We'll choose iterative BFS to avoid recursion stack overflow for deep trees, but both fine.
Edge cases: empty tree -> sum 0.
Now, we need to write a function. We'll assume the tree is represented with a class:
class TreeNode:
def init(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
We'll implement:
def sum_even_level(root: TreeNode) -> int:
if not root:
return 0
from collections import deque
queue = deque([(root, 0)])
total = 0
while queue:
node, level = queue.popleft()
if level % 2 == 0:
total += node.val
if node.left:
queue.append((node.left, level+1))
if node.right:
queue.append((node.right, level+1))
return total
That's it.
But we might also consider: sometimes "even levels" means levels that are even numbers counting from 1? But the problem doesn't specify. In many coding problems, they explicitly say "root is at level 0" or "level 1". Since it's not specified, I'll go with root at level 0. If the problem intended root at level 1, then we would start level=1 and sum when level % 2 == 0. But that would be equivalent to summing at odd levels if we start at 0. Actually: if root at level 1, then even levels are 2,4,... so we would sum nodes at levels 2,4,... That is different. But the problem says "even levels", so it's ambiguous. However, in most contexts, the root is considered level 0 or level 1? Actually, in many tree problems, they say "depth of root is 0" or "level 0". But sometimes they say "level 1". I think it's safer to assume root is level 0 because that's common in CS. But to be thorough, we can mention in explanation that we consider root at level 0. Alternatively, we can ask the user? No.
Maybe the problem expects: if root is at level 1 (odd), then even levels are 2,4,... So the sum would be for levels with even depth? But depth is usually measured from root: root depth 0, so even depths are 0,2,4,... So if they say "levels", it's the same as depth. So I'll go with depth even.
I'll explain: "We consider the root at level 0 (even). Then we sum all nodes at levels 0,2,4,..."
If the problem intended different, we can adjust. But I think it's fine.
Now, we need to produce a final answer with function and explanation.
Let's write an explanation:
Algorithm: We perform a breadth-first traversal (level order) of the tree. For each node, we keep track of its level (starting from 0 for the root). If the level is even, we add the node's value to the running total. At the end, we return the total.
Alternatively, we can do DFS recursively with the same logic.
Complexity: O(n) time, O(w) space for BFS where w is the maximum width of the tree (number of nodes at a level). For DFS, O(h) space where h is the height.
We'll provide the BFS version.
Now, code:
We'll include necessary imports.
I'll produce a complete function.
But note: the problem statement says "Write a function that solves this problem". So we just need to write the function. But we can also include a class definition if we want to run it. Usually, we assume TreeNode is defined. I'll define it for completeness.
So final answer:
python
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_even_level(root: TreeNode) -> int:
"""
Returns the sum of all nodes at even levels in the binary tree.
Level of root is considered 0 (even).
"""
if not root:
return 0
total = 0
queue = deque([(root, 0)])
while queue:
node, level = queue.popleft()
if level % 2 == 0:
total += node.val
if node.left:
queue.append((node.left, level+1))
if node.right:
queue.append((node.right, level+1))
return total
Explanation: ... (as above)
I'll write the explanation in the response.
But the user said: "Please write a function that solves this problem, and explain your algorithm." So we need both.
I'll provide the code and then the explanation.
Now, think: could there be a more efficient way? This is already O(n). No better.
We can also do a DFS without storing level for each node in queue by doing two queues or alternating sums? Actually, we can do level by level: start with level=0, then for each level, if even, sum all nodes in that level. But we still need to traverse all nodes. But we can do:
total = 0
current_level = 0
queue = deque([root])
while queue:
level_size = len(queue)
level_sum = 0
for i in range(level_size):
node = queue.popleft()
level_sum += node.val
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
if current_level % 2 == 0:
total += level_sum
current_level += 1
That avoids storing level per node. It's also O(n) and same space. I'll use this version because it's common in level order traversal.
Let's decide: Which one is simpler? The first one stores level with each node, which is fine. The second one uses a loop per level. Both are good. I'll go with the second because it doesn't need to store extra integer per node in the queue, and it's a standard level-order traversal.
So:
def sum_even_level(root):
if not root:
return 0
from collections import deque
queue = deque([root])
total = 0
level = 0
while queue:
level_size = len(queue)
level_sum = 0
for _ in range(level_size):
node = queue.popleft()
level_sum += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if level % 2 == 0:
total += level_sum
level += 1
return total
That's neat.
I'll choose that.
Now, explanation:
We perform a breadth-first search (BFS) to traverse the tree level by level. For each level, we compute the sum of all node values in that level. We maintain a variable level starting at 0 (root level). After processing all nodes of the current level, we check if level is even (i.e., level % 2 == 0). If so, we add the sum of that level to the total. Then we increment level and proceed to the next level. This ensures we sum exactly the nodes at even levels (0,2,4,...). The algorithm visits each node exactly once, giving O(n) time complexity. The space used by the queue is at most the maximum number of nodes at any level, i.e., O(w) where w is the width of the tree. In the worst case (complete binary tree), the last level can have O(n/2) nodes, so space complexity is O(n). However, in practice, it's bounded by the width.
That's fine.
Now, I'll provide the final answer with code and explanation.
But note: the problem says "binary tree", not necessarily complete. So worst-case width could be O(n) (like a star-shaped tree where root has n-1 children? But binary tree means at most two children per node, so the maximum width is at most the number of nodes in the largest level. In a complete binary tree, the last level can have about n/2 nodes. So space O(n) in worst case. But that's acceptable.
We'll present the solution.
I'll write it in a clear format.
Solution
python
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_even_level(root: TreeNode) -> int:
"""
Returns the sum of all nodes at even levels in the binary tree.
The root is considered to be at level 0 (even).
"""
if not root:
return 0
total = 0
queue = deque([root])
level = 0
while queue:
level_size = len(queue)
level_sum = 0
# Process all nodes at the current level
for _ in range(level_size):
node = queue.popleft()
level_sum += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# If current level is even, add its sum to the total
if level % 2 == 0:
total += level_sum
level += 1
return total
Explanation
We use a breadth‑first search (BFS) approach to traverse the tree level by level.
Initialization
If the tree is empty, return 0.
Create a queue and enqueue the root node.
Initialize total = 0 to accumulate the result and level = 0 (root’s level).
Level‑by‑level traversal
While the queue is not empty:
Determine the number of nodes at the current level (level_size = len(queue)).
Initialize level_sum = 0 to sum node values of this level.
For each node in the current level:
Dequeue the node and add its value to level_sum.
Enqueue its left and right children (if they exist).
After processing all nodes of the level, check if level is even (level % 2 == 0).
If so, add level_sum to total.
Increment level to move to the next level.
Result
After the traversal, total contains the sum of all nodes at even levels (0, 2, 4, …), which is returned.
Complexity Analysis
Time: Each node is visited exactly once, so the time complexity is O(n), where n is the number of nodes in the tree.
Space: The queue stores at most the maximum number of nodes at any level (the tree’s width). In the worst case (a complete binary tree), the last level can contain about n/2 nodes, so the space complexity is O(n). For a very unbalanced tree, the width may be much smaller than n, but the worst‑case bound remains O(n).