zoukankan      html  css  js  c++  java
  • [leetcode]Sum Root to Leaf Numbers @ Python

    原题地址:http://oj.leetcode.com/problems/sum-root-to-leaf-numbers/

    题意:

    Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

    An example is the root-to-leaf path 1->2->3 which represents the number 123.

    Find the total sum of all root-to-leaf numbers.

    For example,

        1
       / 
      2   3
    

    The root-to-leaf path 1->2 represents the number 12.
    The root-to-leaf path 1->3 represents the number 13.

    Return the sum = 12 + 13 = 25.

    解题思路:看到二叉树,我们首先想到递归。比如一棵树如下:

                          1

                         /    

                         2    3

                        /        /  

                        4      5 6     7

         此题求和为sum=124+125+136+137,我们可以使用一个preSum变量来记录从根节点到节点父亲的路径,比如当我们递归的4时,preSum=12,递归到6时,preSum=13,这样就可以了。具体看代码。

    代码:

    # Definition for a  binary tree node
    # 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 sum(self, root, preSum):
            if root==None: return 0
            preSum = preSum*10 + root.val
            if root.left==None and root.right==None: return preSum
            return self.sum(root.left, preSum)+self.sum(root.right, preSum)
            
        def sumNumbers(self, root):
            return self.sum(root, 0)
  • 相关阅读:
    08.设计模式,和ES6let
    H5之本地存储
    07..前后台交互,设计模式
    查询出总数集合
    06.JSON+ajax+跨域+onde 环境搭建 笔记
    05 this 在不同环境下的指向 和正则
    04学习 JS 作用域 继承 闭包
    技术盛宴 | 从实战浅析运营商云资源池—解析流量模型
    从实战浅析运营商云资源池网络—技术的抉择
    ovn-sbctl
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3721420.html
Copyright © 2011-2022 走看看