每日一道算法题--leetcode 129--求根到叶子节点数字之和--python

404 阅读1分钟

【题目描述】

【代码思路】

从根结点开始就向下传递的是current_st这个变量,先把每个结点用str+str的方式变成一个str,比如'1','2','3'最终变为'123'。对于左右子树都递归调用深度优先搜索,一旦到了叶结点处,将str转换成int,累加到result中。

【源代码】

class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.result=0
        self.dfs(root,'')
        return self.result
        
    def dfs(self,root,current_str):
        if not root:return
        current_str=current_str+str(root.val)
        if root.left:
            self.dfs(root.left,current_str)
        if root.right:
            self.dfs(root.right,current_str)
        if not root.left and not root.right:
            self.result+=int(current_str)