112. Path Sum

86 阅读1分钟

题目描述

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.

解题思路

这个题目我们的思路是: 在遍历二叉树的同时, 我们判断当前节点是不是叶子节点 (没有左右子树) 并且 当前节点的 val 等于 target, 至于target, 我们可以用sum 减去每一次遍历到的 根节点的val, 剩下的值就是 子节点需要的target

示例代码

func hasPathSum(_ root: TreeNode?, _ sum: Int) -> Bool {

    if root == nil {
        return false
    }

    if root?.left == nil && root?.right == nil && root?.val == sum  {
        return true
    }

    return hasPathSum(root?.left, sum - root!.val) || hasPathSum(root?.right, sum - root!.val)
}