leetcode题解

【Leetcode】112—Path Sum

2019-07-16  本文已影响0人  Gaoyt__
一、题目描述

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。

二、代码实现
方法一、深度优先搜索(DFS)

找到所有存在的路径和,判断sum是否在其中。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        def dfs(root, dist, res):
            if not root.left and not root.right:
                res.append(dist + root.val)
                
            if root.left:
                dfs(root.left, dist + root.val, res)
            
            if root.right:
                dfs(root.right, dist + root.val, res)
            
            
        if not root: return False
        res = []
        dfs(root, 0, res)
        if sum in res: return True
        else: return False
方法二、递归
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root: return False
        if not root.left and not root.right:
            return root.val == sum
        elif root.left and not root.right:
            return self.hasPathSum(root.left, sum-root.val)
        elif not root.left and root.right:
            return self.hasPathSum(root.right, sum-root.val)
        else:
            return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
上一篇下一篇

猜你喜欢

热点阅读