You are given a binary tree. Write a function to find the "sum of all nodes" with only one child. Please write a function that solves this problem, and explain your algorithm.
Assistant
We need to write a function that finds the sum of all nodes that have exactly one child in a binary tree. So we traverse the tree, at each node check the number of children (left and right). If exactly one child exists (either left is null and right is not null, or left is not null and right is null), then add that node's value to the sum. Then continue traversal. The sum includes all such nodes.
We need to write a function. The problem statement: "You are given a binary tree. Write a function to find the 'sum of all nodes' with only one child." So we need to output sum. We need to explain algorithm. Also we need to consider the tree representation. Typically a binary tree node has fields: val, left, right. So we can write in Python, maybe. Or any language. We'll choose Python for simplicity. We'll define a TreeNode class. Then function sum_of_nodes_with_one_child(root). We'll do a recursive DFS or iterative. Let's do recursive for clarity. Base case: if root is None, return 0. Then compute left_sum = recursive on left, right_sum = recursive on right. Then check if root has exactly one child: (root.left is None) != (root.right is None) i.e., XOR. Or explicitly: if (root.left is not None and root.right is None) or (root.left is None and root.right is not None). Then add root.val to sum. Then total = root.val (if condition) + left_sum + right_sum. Return total.
Alternatively, we can do iterative BFS.
Complexity: O(n) time, O(h) space for recursion stack.
Explain algorithm: We traverse each node exactly once, check its children count, and accumulate sum accordingly.
We'll produce code.
But also consider corner cases: empty tree returns 0. Single node (root) has zero children, so not counted. Leaves have no children, not counted. Nodes with both children not counted. Nodes with exactly one child count.
Now produce final answer: explanation and code.
Solution Explanation
We need to compute the sum of values of all nodes in a binary tree that have exactly one child (either only a left child or only a right child).
The approach is straightforward: traverse the tree (e.g., depth‑first), and at each node check how many children it has. If the node has exactly one child, add its value to a running total. The traversal ensures we visit every node once, so the total sum is accumulated correctly.
Algorithm Steps
Base case: If the current node is None, return 0 (no contribution to the sum).
Recursive step:
Recursively compute the sum from the left subtree (left_sum).
Recursively compute the sum from the right subtree (right_sum).
Check child count:
Count how many non‑null children the node has.
If the count is exactly 1, include the node's value in the sum for this subtree.
Combine: total = (node.val if exactly_one_child else 0) + left_sum + right_sum
Return total.
Correctness Proof
We prove by structural induction on the binary tree that the function sum_one_child(node) returns the sum of values of all nodes in the subtree rooted at node that have exactly one child.
Base: If node is None, the subtree is empty. There are no nodes with one child, so the sum is 0. The function returns 0.
Inductive step: Assume the recursive calls correctly compute the sums for the left and right subtrees (i.e., left_sum and right_sum are correct). Consider the current node. There are three possibilities for its children:
0 children (leaf): The node does not have exactly one child, so it contributes 0. The total sum for the subtree is left_sum + right_sum. Since both subtrees are leaves, left_sum and right_sum are 0. The function returns 0, which is correct.
2 children: The node does not have exactly one child, so it contributes 0. The total sum is left_sum + right_sum. The function returns that, which by induction hypothesis equals the sum of all qualifying nodes in the subtrees. Hence correct.
Exactly 1 child: The node contributes its value node.val. The total sum is node.val + left_sum + right_sum. The function returns exactly that, and by induction hypothesis left_sum and right_sum are correct. Hence the sum includes the current node and all qualifying nodes in the subtrees.
Thus, by induction, the algorithm correctly computes the required sum for any binary tree.
Complexity Analysis
Time: Each node is visited exactly once, and the work per node is O(1). Hence total time is O(n) where n is the number of nodes.
Space: The recursion stack uses O(h) space, where h is the height of the tree (worst‑case O(n) for a skewed tree, O(log n) for a balanced tree). No additional data structures are used.
Reference Implementation (Python)
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_of_nodes_with_one_child(root: TreeNode) -> int:
"""
Returns the sum of values of all nodes that have exactly one child.
"""
if root is None:
return 0
# Recursively compute sums for subtrees
left_sum = sum_of_nodes_with_one_child(root.left)
right_sum = sum_of_nodes_with_one_child(root.right)
# Determine if current node has exactly one child
has_left = root.left is not None
has_right = root.right is not None
exactly_one_child = (has_left and not has_right) or (not has_left and has_right)
# Include current node's value if condition holds
current_val = root.val if exactly_one_child else 0
return current_val + left_sum + right_sum
# Example usage:
# Construct a tree:
# 1
# / \
# 2 3
# / \
# 4 5
# / \ /
# 6 7 8
#
# Nodes with exactly one child: 2 (has left only), 3 (has right only), 5 (has left only)
# Sum = 2 + 3 + 5 = 10
if __name__ == "__main__":
# Build the example tree
n6 = TreeNode(6)
n7 = TreeNode(7)
n8 = TreeNode(8)
n4 = TreeNode(4, n6, n7)
n5 = TreeNode(5, n8, None)
n2 = TreeNode(2, n4, None)
n3 = TreeNode(3, None, n5)
root = TreeNode(1, n2, n3)
print(sum_of_nodes_with_one_child(root)) # Output: 10
The function can be easily adapted to other languages (e.g., Java, C++) by following the same recursive logic.