【LeetCode每天一题】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.

Note: A leaf is a node with no children.

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.

 

思路


  这道题我们使用递归进行解决,递归结束条件为节点为空时返回False,还有一个就是就是当前节点为叶子节点(叶子节点就是左右节点为空),并且sum是否为0时返回True。

解决代码


 

 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  not root:            # 空节点直接返回
16             return False
17         if root and not root.left and not root.right and root.val == sum:   # 当前节点为叶子节点,并且sum为0
18             return True
19         return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)    # 左右节分别进行判断

如果我们需要得到满足路径的值呢?

Example:  Given the below binary tree and sum = 22,

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

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

思路

  和上面那道题的解决方式一样,只不过多一个path和res来记录节点路径和结果列表。还是使用递归。
解决代码

 
 
 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 pathSum(self, root, sum):
10         """
11         :type root: TreeNode
12         :type sum: int
13         :rtype: List[List[int]]
14         """
15         if not root:
16             return []
17         res = []
18         self.path(root, sum, res, [])
19         return res
20         
21     def path(self, root, sum, res, path):
22         if not root:           # 为空直接返回
23             return
24         if not root.left and not root.right and root.val == sum:   # 判断该叶子节点的路径是否满足条件
25             path.append(root.val)
26             res.append(path)
27             return
28         self.path(root.left, sum-root.val, res, path+[root.val])     # 该节点的左子树
29         self.path(root.right, sum-root.val, res,path+[root.val])     # 该节点的右子树

转载于:https://www.cnblogs.com/GoodRnne/p/10878016.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值