zoukankan      html  css  js  c++  java
  • 22.112.leetcode_path_sum

    1.题目描述

    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.

    给一个二叉树和一个sum,判断二叉树中是否有一个路径的和等于sum

    2.题目分析

    ①此处的路径应该是完整路径的意思,所以当两个子节点都为空时才算完整路径。②如果用节点值求和的话,比较麻烦。不如直接用sum去减节点值。

    3.解题思路

     1 # Definition for a binary tree node.
     2 # class TreeNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 
     8 class Solution(object):
     9     def hasPathSum(self, root, sum):
    10         """
    11         :type root: TreeNode
    12         :type sum: int
    13         :rtype: bool
    14         """
    15         if root==None: #遍历到空节点,说明此条完整路径不符合条件
    16             return False
    17         if sum-root.val==0 and root.left==None and root.right==None: #满足完整路径及和为sum的条件,返回true
    18             return True
    19         else:  #没有结束完整路径的遍历
    20             sum-=root.val #sum减去当前节点值
    21             return self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum) #继续遍历,其中一个为true,返回true
  • 相关阅读:
    692. Top K Frequent Words
    659. Split Array into Consecutive Subsequences
    hdu5015矩阵快速幂
    codefroces 450B矩阵快速幂
    ural Ambitious Experiment 树状数组
    poj3254 状态压缩dp
    poj2686 状压dp入门
    hdu4763 kmp
    hdu4847 kmp
    hdu3294 manacher
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8439944.html
Copyright © 2011-2022 走看看