zoukankan      html  css  js  c++  java
  • LeetCode 112. Path Sum 20170705 部分之前做了没写的题目

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /        
            7    2      1
    

    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

    题目大意:给定一个二叉树和一个总和,问是否存在一个从根节点到叶节点的路径使该路径的和等于所给的总和。

    解题思路:该题可以用递归的方法,遍历整棵树,从根节点开始,往下走,每走一步,都把sum减掉父节点的值,如果走到了叶子节点的位置,也就是该节点没有左子节点也没有右子节点,则判断当前的sum跟叶子节点上的值是否相当。如果相等,则说明该沿着该路径从根节点走到该叶子节点上所有节点的值的和等于sum。由于只要有任意一条路径的和等于sum就返回true,所以在递归时采用左子树or右子树的方式。

    class Solution(object):
      def hasPathSum(self, root, sum):
        if root == None:
          return False
        elif root.left == None and root.right == None:
          if root.val == sum:
            return True
          else:
            return False
        else:
          return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)

  • 相关阅读:
    猜数字和楼层扔鸡蛋问题
    python+selenium+unittest----skip(跳过用例)
    python+selenium+unittest----常用属性详解(框架属性详解)
    php----等比缩放图片
    Vue----生命周期
    js----定义变量的几种方式
    quartz(7)-源码分析
    quartz(6)--集群
    quartz(5)--作业管理和存储
    quartz(4)--quartz.properties文件
  • 原文地址:https://www.cnblogs.com/fangdai/p/7121654.html
Copyright © 2011-2022 走看看