# 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], s: int) -> int:
if node is None:
return 0
s = (s << 1) | node.val
if node.left == None and node.right == None:
return s
return dfs(node.left, s) + dfs(node.right, s)
return dfs(root, 0)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumRootToLeaf(root *TreeNode) int {
return helper(root, 0)
}
func helper(node *TreeNode, sum int) int {
if node == nil {
return 0
}
sum = sum << 1 + node.Val
if node.Left == nil && node.Right == nil {
return sum
}
return helper(node.Left, sum) + helper(node.Right, sum)
}