[LeetCode]题解(python):112 Path Sum
Posted loadofleaf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]题解(python):112 Path Sum相关的知识,希望对你有一定的参考价值。
题目来源
https://leetcode.com/problems/path-sum/
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.
题意分析
Input: a binary tree, sum
Output: True or False
Conditions:判断是否存在一条路径,从root-leaf的路径,使得路径的value的和等于sum
题目思路
递归遍历,通过一个不断递减的sum值去判断。
AC代码(Python)
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 root.left == None and root.right == None: 18 return root.val == sum 19 return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val) 20
以上是关于[LeetCode]题解(python):112 Path Sum的主要内容,如果未能解决你的问题,请参考以下文章
leetcode349 python3 112ms 求两个数组的交集
Educational Codeforces Round 112 (Rated for Div. 2)-A. PizzaForces-题解
Educational Codeforces Round 112 (Rated for Div. 2)-A. PizzaForces-题解