根到叶子结点的总和

'''
        1
       / \
      2   3
      
12 + 13 = 25
'''


class TreeNode:
    def __init__(self,val):
        self.val = val
        self.left = None
        self.right = None

class Solution:
    def sum_numbers(self,root):
        self.ans = 0
        if not root:
            return self.root
        def dfs(num,root):
            num = num * 10 + root.val
            if not root.left and not root.right:
                self.ans += num
            if  root.left:
                dfs(num,root.left)
            if  root.right:
                dfs(num,root.right)
        dfs(0,root)
        return self.ans

def main():
    root = TreeNode(1)
    n1 = TreeNode(2)
    n2 = TreeNode(3)
    root.left = n1
    root.right = n2
    
    r = Solution()
    print(r.sum_numbers(root))


if __name__ == "__main__":
    main()
posted @ 2022-08-25 22:59  Ray_chen  阅读(19)  评论(0编辑  收藏  举报