【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])     # 该节点的右子树
posted @ 2019-05-16 21:06  GoodRnne  阅读(161)  评论(0编辑  收藏  举报