[Golang][Leetcode][BinaryTree]刷題系列-112-Path Sum

Contents
112. Path Sum
Level : Easy
原題連結 : Click
題目 :
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.
Example :
Note
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true
Example 2:
Input: root = [1,2,3], targetSum = 5 Output: false
Example 3:
Input: root = [1,2], targetSum = 0 Output: false
解題思路 :
- 這題需要我把檢查是否有任何一個path的和等於他給的targetSum
- 這題考察的其實的不外乎就是對dfs的概念,加上若是用recursive的方式會更簡潔,所以一方面也考察對於recursive code的掌握度,誰作為回傳值or誰作為argument…等
- 解法1是我一開始的答案,非常直觀的寫法,且time complexity是O(n)
- 看完解法1可以繼續看我從討論區得到的解法2,這個解法就更簡潔了,是利用targetSum進行減法去做檢查,是不是更高明了呢!? 趕快學起來!
Recursive解法-1
- time complexity: O(n) , space complexity: O(1)
Runtime: 4 ms, faster than 91.44% of Go online submissions for Path Sum.
|
|
Recursive解法-2
- time complexity: O(n) , space complexity: O(1)
Runtime: 4 ms, faster than 91.44% of Go online submissions for Path Sum.
|
|
最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!