1022. Sum of Root to Leaf Binary Numbers

1022. Sum of Root To Leaf Binary Numbers #

Problem #

You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit.

For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers.

The test cases are generated so that the answer fits in a 32-bits integer.

Example 1:

Input: root = [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Example 2:

Input: root = [0]
Output: 0

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].

  • Node.val is 0 or 1.

Summary #

Given a binary tree whose node values are all 0 or 1, each path from the root node to a leaf node represents a binary number starting from the most significant bit.

Return the sum of the numbers represented by all paths from the root node to leaf nodes.

Solution Approach #

Use recursion to perform a postorder traversal (left subtree - right subtree - root node) on the root node root.

Return value of the recursive function:

When recursively traversing each node, calculating the numeric value sum represented from the root node to the currently visited node uses the previous calculation result, so the return value of the recursive function is the calculated result value of the currently visited node.

Logic of the recursive function:

  • If the current traversal node is nil, it means this level of recursion has ended, so directly return 0.

  • If the currently visited node is a leaf node, return the numeric value sum represented from the root node to this node.

  • If the currently visited node is not a leaf node, return the sum of the results corresponding to the left subtree and the right subtree.

Code #

package leetcode

import "github.com/halfrost/LeetCode-Go/structures"

// TreeNode define
type TreeNode = structures.TreeNode

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumRootToLeaf(root *TreeNode) int {
	var dfs func(*TreeNode, int) int
	dfs = func(node *TreeNode, sum int) int {
		if node == nil {
			return 0
		}
		sum = sum<<1 | node.Val
		// The previous line can also be written as sum = sum*2 + node.Val
		if node.Left == nil && node.Right == nil {
			return sum
		}
		return dfs(node.Left, sum) + dfs(node.Right, sum)
	}
	return dfs(root, 0)
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文