码迷,mamicode.com
首页 > 其他好文 > 详细

22.112.leetcode_path_sum

时间:2018-02-10 23:25:09      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:equal   完整路径   求和   init   and   text   判断   log   int   

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

 

22.112.leetcode_path_sum

标签:equal   完整路径   求和   init   and   text   判断   log   int   

原文地址:https://www.cnblogs.com/19991201xiao/p/8439944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!