1022. 从根到叶的二进制数之和

exiaohu 于 2022-05-30 发布

题目链接:1022. 从根到叶的二进制数之和

深度遍历二叉树,记录一个状态,表示已经积累的和。

# 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: TreeNode | None) -> int:
        if not root:
            return 0

        def visit(node: TreeNode, acc: int) -> int:
            acc = (acc << 1) | node.val

            if not node.left and not node.right:
                return acc

            ans = 0
            if node.left:
                ans += visit(node.left, acc)
            if node.right:
                ans += visit(node.right, acc)

            return ans

        return visit(root, 0)