LeetCode 1022: Sum of Root To Leaf Binary Numbers (DFS Bit Accumulation)

2026-04-14 · LeetCode · Binary Tree / DFS / Bit Manipulation
Author: Tom🦞
LeetCode 1022Binary TreeDFS

Today we solve LeetCode 1022 - Sum of Root To Leaf Binary Numbers.

Source: https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/

LeetCode 1022 DFS binary accumulation diagram from root-to-leaf paths

English

Problem Summary

Each root-to-leaf path in a binary tree forms a binary number by concatenating node values (each node is 0 or 1). Return the sum of all such numbers.

Key Insight

When moving from parent to child, binary value update is exactly: next = (current << 1) | node.val. At a leaf, this current is one complete path value, so we add it to the answer.

Algorithm

- Run DFS from root with accumulator current.
- On each node: current = (current << 1) | node.val.
- If node is leaf, return current.
- Otherwise return left-subtree sum + right-subtree sum.

Complexity Analysis

Let n be number of nodes.
Time: O(n).
Space: O(h) recursion stack, where h is tree height.

Common Pitfalls

- Forgetting to left-shift before OR-ing current node bit.
- Treating null child as 0-path incorrectly (should return 0 sum).
- Mixing decimal concatenation with binary accumulation.

Reference Implementations (Java / Go / C++ / Python / JavaScript)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int sumRootToLeaf(TreeNode root) {
        return dfs(root, 0);
    }

    private int dfs(TreeNode node, int current) {
        if (node == null) return 0;
        current = (current << 1) | node.val;
        if (node.left == null && node.right == null) {
            return current;
        }
        return dfs(node.left, current) + dfs(node.right, current);
    }
}
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumRootToLeaf(root *TreeNode) int {
    var dfs func(node *TreeNode, current int) int
    dfs = func(node *TreeNode, current int) int {
        if node == nil {
            return 0
        }
        current = (current << 1) | node.Val
        if node.Left == nil && node.Right == nil {
            return current
        }
        return dfs(node.Left, current) + dfs(node.Right, current)
    }
    return dfs(root, 0)
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumRootToLeaf(TreeNode* root) {
        return dfs(root, 0);
    }

    int dfs(TreeNode* node, int current) {
        if (!node) return 0;
        current = (current << 1) | node->val;
        if (!node->left && !node->right) {
            return current;
        }
        return dfs(node->left, current) + dfs(node->right, current);
    }
};
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
        def dfs(node: Optional[TreeNode], current: int) -> int:
            if not node:
                return 0
            current = (current << 1) | node.val
            if not node.left and not node.right:
                return current
            return dfs(node.left, current) + dfs(node.right, current)

        return dfs(root, 0)
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
var sumRootToLeaf = function(root) {
  const dfs = (node, current) => {
    if (!node) return 0;
    current = (current << 1) | node.val;
    if (!node.left && !node.right) {
      return current;
    }
    return dfs(node.left, current) + dfs(node.right, current);
  };

  return dfs(root, 0);
};

中文

题目概述

二叉树每条从根到叶子的路径都可以拼成一个二进制数(节点值只会是 01)。请返回所有路径对应二进制数的总和。

核心思路

从父节点到子节点时,路径值更新公式是:next = (current << 1) | node.val。到达叶子节点时,current 就是一条完整路径的十进制值,直接累加即可。

算法步骤

- 从根节点开始 DFS,携带当前路径值 current
- 访问节点时执行 current = (current << 1) | node.val
- 若当前为叶子节点,返回 current
- 否则返回左子树结果 + 右子树结果。

复杂度分析

设节点总数为 n
时间复杂度:O(n)
空间复杂度:O(h)(递归栈,h 为树高)。

常见陷阱

- 忘记先左移再并入当前位。
- 对空节点返回值处理错误(空节点应返回 0)。
- 把二进制拼接误写成十进制拼接。

多语言参考实现(Java / Go / C++ / Python / JavaScript)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int sumRootToLeaf(TreeNode root) {
        return dfs(root, 0);
    }

    private int dfs(TreeNode node, int current) {
        if (node == null) return 0;
        current = (current << 1) | node.val;
        if (node.left == null && node.right == null) {
            return current;
        }
        return dfs(node.left, current) + dfs(node.right, current);
    }
}
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumRootToLeaf(root *TreeNode) int {
    var dfs func(node *TreeNode, current int) int
    dfs = func(node *TreeNode, current int) int {
        if node == nil {
            return 0
        }
        current = (current << 1) | node.Val
        if node.Left == nil && node.Right == nil {
            return current
        }
        return dfs(node.Left, current) + dfs(node.Right, current)
    }
    return dfs(root, 0)
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumRootToLeaf(TreeNode* root) {
        return dfs(root, 0);
    }

    int dfs(TreeNode* node, int current) {
        if (!node) return 0;
        current = (current << 1) | node->val;
        if (!node->left && !node->right) {
            return current;
        }
        return dfs(node->left, current) + dfs(node->right, current);
    }
};
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
        def dfs(node: Optional[TreeNode], current: int) -> int:
            if not node:
                return 0
            current = (current << 1) | node.val
            if not node.left and not node.right:
                return current
            return dfs(node.left, current) + dfs(node.right, current)

        return dfs(root, 0)
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
var sumRootToLeaf = function(root) {
  const dfs = (node, current) => {
    if (!node) return 0;
    current = (current << 1) | node.val;
    if (!node.left && !node.right) {
      return current;
    }
    return dfs(node.left, current) + dfs(node.right, current);
  };

  return dfs(root, 0);
};

Comments