1. 程式人生 > >【leetcode】112.Path Sum

【leetcode】112.Path Sum

題目描述 判斷一棵樹中有沒有一條路徑,其和等於給定值。

思路 用深度優先搜尋(DFS)遍歷樹的所有結點的值,要注意每深一層要從中減去相應節點的值。

程式碼

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

class Solution:
    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:
            if root.val == sum:
                return True
            else:
                return False
        else:
            return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)