🖋

LeetCode 112. Path Sum

に公開

はじめに

LeetCode 「112. Path Sum」の問題をGoで解きました。

問題

https://leetcode.com/problems/path-sum/description

問題文

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

和訳
二分木のルートと整数 targetSum が与えられたとき、その木にルートからリーフへのパスがあり、そのパスに沿ったすべての値の合計が targetSum と等しい場合に真を返す。

リーフとは、子を持たないノードである。

         5          
      /     \        
     4       8    
   /        /  \    
  11       13   4
 /  \            \
7    2            1 
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.

5 + 4 + 11 + 2 = 22

         1          
      /     \        
     2       3    
Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There are two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

制約

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

解答1:DFS(深さ優先検索・再帰)

二分木のルートからリーフまでの合計がtargetSumと等しいか判定します。
部分的な経路ではなく、リーフに到達するまでを求めていることがポイントです。
1本の道を深く辿ることになるので、DFSで解くのが直感的です。

経路を合計をどう管理するかについては、 node.Val を足していく方法と引いていく方法があります。
引いていく方法の方が、再帰的に実装した場合に効率的に解くことができます。

コード

func hasPathSum(root *TreeNode, targetSum int) bool {
    if root == nil {
        return false
    }

    // リーフノードに到達したら、合計が一致するか確認
    if root.Left == nil && root.Right == nil {
        return root.Val == targetSum
    }

    // 左右のどちらかに一致するパスがあればOK
    return hasPathSum(root.Left, targetSum - root.Val) ||
           hasPathSum(root.Right, targetSum - root.Val)
}

コード(足していく方法)

func hasPathSum(root *TreeNode, targetSum int) bool {
    if root == nil {
        return false
    }
    return dfs(root, 0, targetSum)
}

func dfs(node *TreeNode, current int, targetSum int) bool {
    if node == nil {
        return false
    }
    current += node.Val

    if node.Left == nil && node.Right == nil {
        return current == targetSum
    }

    return dfs(node.Left, current, targetSum) ||
           dfs(node.Right, current, targetSum)
}

計算量

  • 時間的計算量:O(n)
    • n はノード数(各ノードを1回ずつ訪れる)
  • 空間的計算量:O(h)
    • h は木の高さ(再帰呼び出しのスタックが木の高さ分使われる)

参考

二分木の問題は、以下の記事でも紹介していますので、参考にしてください。

GitHubで編集を提案

Discussion