Jump Game II @ LeetCode (Python)
Longest Consecutive Sequence @ LeetCode (Python)

Sum Root to Leaf Numbers @ LeetCode (Python)

kitt posted @ 2014年2月18日 19:50 in LeetCode , 1683 阅读

父节点把已有的值传给子节点, 子节点把这个值乘以10再加上自身的值。

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

class Solution:
    # @param root, a tree node
    # @return an integer
    def sumNumbers(self, root):
        if root == None: return 0
        if root.left == None and root.right == None: return root.val
        Solution.res = 0
        if root.left: self.getSum(root.left, root.val)
        if root.right: self.getSum(root.right, root.val)
        return Solution.res
    
    def getSum(self, root, valFromParent):
        if root == None: return
        if root.left == None and root.right == None:
            Solution.res += 10 * valFromParent + root.val
        self.getSum(root.left, 10 * valFromParent + root.val)
        self.getSum(root.right, 10 * valFromParent + root.val)
        return

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter