We need to solve: Given a binary tree, find the sum of all nodes at odd levels. That is, sum of node values where the depth (starting from root at level 1) is odd? Or root at level 0? The problem statement says odd levels. Usually level 1 is odd, level 2 even, etc. But need to be clear: If root is level 1, then odd levels are 1,3,5,... So sum nodes at these depths. Alternatively, if root is level 0, odd levels are 1,3,... But common convention: root at level 0 or 1? Many problems define root as level 1. The phrase "odd levels" might mean level numbers that are odd. So we can define root at level 1 and then odd levels = 1,3,5,... But it's ambiguous. We'll choose a definition and note it. Since it's a function, we can choose either, but we'll assume root is at level 1 (odd). Then we sum nodes at levels 1,3,5,... In code, we can track depth and check if depth % 2 == 1.
We need to write a function. We'll implement in Python for simplicity, assuming we have a TreeNode class with val, left, right.
Algorithm: Use BFS (level order) or DFS. BFS: traverse level by level, keep a level count, and for odd levels add sum of nodes at that level. Or DFS: pass depth, if odd then add node value, then recurse for children with depth+1.
Time complexity O(n) where n is number of nodes, space O(h) for DFS or O(width) for BFS.
I'll provide a DFS solution as it's straightforward.
Implementation:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_odd_levels(root: TreeNode, depth=1) -> int:
if not root:
return 0
total = root.val if depth % 2 == 1 else 0
total += sum_odd_levels(root.left, depth+1)
total += sum_odd_levels(root.right, depth+1)
return total
But careful: This function uses recursion and default depth=1. But if called externally, we want to call with just root. So we can define a helper or use an internal function.
Alternatively, we can write:
def sum_odd_level_nodes(root):
def dfs(node, level):
if not node:
return 0
current = node.val if level % 2 == 1 else 0
return current + dfs(node.left, level+1) + dfs(node.right, level+1)
return dfs(root, 1)
That's clean.
We could also do BFS:
from collections import deque
def sum_odd_levels_bfs(root):
if not root:
return 0
q = deque([(root, 1)])
total = 0
while q:
node, level = q.popleft()
if level % 2 == 1:
total += node.val
if node.left:
q.append((node.left, level+1))
if node.right:
q.append((node.right, level+1))
return total
But BFS uses queue and might be slightly less memory efficient for very deep trees but similar.
We'll provide DFS solution as it's simpler.
Now, we need to explain algorithm.
We'll include:
- Approach: Depth-first search traversal.
- We maintain current level (starting at 1 for root). For each node, if level is odd, add its value to sum.
- Recursively process left and right children with level+1.
- Base case: node is None, return 0.
- Complexity: O(n) time, O(h) space (call stack) where h is height of tree.
- Edge cases: empty tree returns 0.
That's it.
Now produce final answer with function and explanation.
Solution Explanation
We are asked to compute the sum of all node values in a binary tree that lie on odd-numbered levels.
We assume the root is at level 1 (odd). Thus, levels 1, 3, 5, … are odd; levels 2, 4, 6, … are even.
Algorithm
We can traverse the entire tree using depth‑first search (DFS). While recursing, we pass the current depth. Whenever we visit a node, we check whether its depth is odd: if so, we add its value to the sum. Then we recursively process its left and right children with depth increased by one.
Steps:
- If the current node is
None, return 0 (base case).
- Compute
current = node.val if depth is odd, otherwise 0.
- Recurse on the left child with
depth+1 and on the right child with depth+1.
- Return
current + left_sum + right_sum.
The outermost call starts with depth = 1.
Correctness Proof
We prove that the algorithm returns the sum of all nodes on odd levels by structural induction on the tree.
Definitions:
Let S(T, d) denote the sum returned by the algorithm for subtree T when its root T.root is at depth d.
Base case: If the subtree is empty (T.root is None), the algorithm returns 0. This is correct because there are no nodes to contribute.
Inductive step: Assume the algorithm works correctly for the left and right subtrees (i.e., S(T.left, d+1) equals the sum of nodes on odd levels within the left subtree when its root is at depth d+1, and similarly for the right). Consider a non‑empty tree T with root r at depth d.
- If
d is odd, the algorithm includes r.val in current; otherwise it does not. This correctly accounts for whether the root contributes to the odd‑level sum.
- The algorithm then recursively computes
S(T.left, d+1) and S(T.right, d+1). By the induction hypothesis, these sums correctly account for all nodes in the left and right subtrees that lie on odd levels (note that the level of every child is d+1 relative to the original root, so the parity of each descendant’s depth is determined correctly by the recursive calls).
- Adding
current to the recursive results yields the total sum of all nodes in T that are on odd levels.
Thus, by induction, the algorithm is correct for any binary tree.
Complexity Analysis
- Time: Each node is visited exactly once, so the running time is
O(n), where n is the number of nodes.
- Space: The recursion depth equals the height
h of the tree. In the worst case (a degenerate tree), this is O(n). In a balanced tree, it is O(log n). Apart from the recursion stack, only constant extra space is used.
Reference Implementation (Python)
class TreeNode:
"""Binary tree node."""
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_odd_level_nodes(root: TreeNode) -> int:
"""
Returns the sum of all node values at odd levels (root = level 1) in the binary tree.
"""
def dfs(node: TreeNode, depth: int) -> int:
if not node:
return 0
# Include node value only if depth is odd
current = node.val if depth % 2 == 1 else 0
left_sum = dfs(node.left, depth + 1)
right_sum = dfs(node.right, depth + 1)
return current + left_sum + right_sum
return dfs(root, 1) # Start with root at depth 1
Usage Example:
# Construct a sample tree:
# 1
# / \
# 2 3
# / \ \
# 4 5 6
# /
# 7
root = TreeNode(1,
TreeNode(2,
TreeNode(4,
TreeNode(7)),
TreeNode(5)),
TreeNode(3,
None,
TreeNode(6)))
print(sum_odd_level_nodes(root)) # Output: 1 + 4 + 5 + 6 = 16
In the example, the odd levels are:
- Level 1: node 1 → sum = 1
- Level 3: nodes 4, 5, 6 → sum = 4+5+6 = 15
Total = 16. The function correctly computes that sum.