Leetcode Note: Go - Sum of Root to Leaf Binary Numbers

Sum of Root To Leaf Binary Numbers - LeetCode
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/

  • Go 言語で取り組んだメモ

回答

Sum of Root To Leaf Binary Numbers - LeetCode
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/solution/

Go recursive solution - LeetCode Discuss
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/760466/Go-recursive-solution

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func sumRootToLeaf(root *TreeNode) int {
    return dfs(root, 0)
}

func dfs(root *TreeNode, currSum int) int {
    currSum = (currSum << 1) | root.Val
    
    if root.Left == nil && root.Right == nil {
        return currSum
    }
    
    total := 0
    if root.Left != nil {
        total += dfs(root.Left, currSum)
    }
    
    if root.Right != nil {
        total += dfs(root.Right, currSum)
    }
    
    return total
}