首页 > 代码库 > 【leetcode】Sum Root to leaf Numbers

【leetcode】Sum Root to leaf Numbers

简单的二叉树的先根遍历模板的应用

class Solution:
    # @param root, a tree node
    # @return an integer
    def hehe(self, num, root):
        #再原来的基础上*10,再加上当前的root.val
        num = num * 10 + root.val
        
        #是叶子节点了,则返回获得的路径值,通过这个判断,就保证了上一条语句
        #的root是不空的
        if None == root.left and None == root.right:
            return num
            
        #分别判断左右孩子    
        left = 0
        if root.left:
            left = self.hehe(num, root.left)
            
        right = 0
        if root.right:
            right = self.hehe(num, root.right)
            
        #返回两部分的和值  
        return right + left
        
        
    def sumNumbers(self, root):
        if None == root: return 0
        return self.hehe(0, root)
        
        


【leetcode】Sum Root to leaf Numbers