Sum of Root To Leaf Binary Numbers (Leetcode 1022)

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

class Solution:

    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
    
        global summ
        summ=0
        
        def fun(root,string):
        
            global summ
            if(root is not None):
                string=string+str(root.val)
                if(root.left is None and root.right is None):
                    num=int(string)
                    t=0
                    c=0
                    while(num):
                        if(num%10==1):
                            t=t+2**c
                        c+=1
                        num=num//10
                    summ+=t
                    return
                fun(root.left,string)
                fun(root.right,string)
        
        fun(root,"")
        return summ

Last updated