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

leetcode112 Path Sum

时间:2020-02-13 22:44:08      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:pre   pat   nbsp   col   节点   with   path sum   应该   treenode   

 1 """
 2 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.
 3 Note: A leaf is a node with no children.
 4 Example:
 5 Given the below binary tree and sum = 22,
 6       5
 7      /  8     4   8
 9    /   / 10   11  13  4
11  /  \      12 7    2      1
13 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
14 """
15 """
16 这道求二叉树的路径需要用深度优先算法DFS的思想来遍历每一条完整的路径,
17 也就是利用递归不停找子节点的左右子节点,而调用递归函数的参数只有当前节点和sum值。
18 首先,如果输入的是一个空节点,则直接返回false,
19 如果输入的只有一个根节点,则比较当前根节点的值和参数sum值是否相同,
20 若相同,返回true,否则false。
21 这个条件也是递归的终止条件。
22 下面我们就要开始递归了,由于函数的返回值是Ture/False,
23 我们可以同时两个方向一起递归,中间用或||连接,只要有一个是True,整个结果就是True。
24 递归左右节点时,这时候的sum值应该是原sum值减去当前节点的值。
25 """
26 class TreeNode:
27     def __init__(self, x):
28         self.val = x
29         self.left = None
30         self.right = None
31 
32 class Solution:
33     def hasPathSum(self, root, sum):
34         if root == None:
35             return False
36         if root.left == None and root.right == None: #!!!判别条件
37             return root.val == sum
38         return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
39                         #!!!sum值不断改变为 sum - root.val

 

leetcode112 Path Sum

标签:pre   pat   nbsp   col   节点   with   path sum   应该   treenode   

原文地址:https://www.cnblogs.com/yawenw/p/12305559.html

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