Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2435241

Browse files
112. Path Sum
1 parent 19e2eb7 commit 2435241

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

‎112.PathSum.kt‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Example:
3+
* var ti = TreeNode(5)
4+
* var v = ti.`val`
5+
* Definition for a binary tree node.
6+
* class TreeNode(var `val`: Int) {
7+
* var left: TreeNode? = null
8+
* var right: TreeNode? = null
9+
* }
10+
*/
11+
//https://leetcode.com/problems/path-sum/description
12+
class Solution {
13+
fun hasPathSum(root: TreeNode?, targetSum: Int): Boolean {
14+
return dfs(root, 0, targetSum)
15+
}
16+
17+
fun dfs(node: TreeNode?, sum: Int, targetSum: Int): Boolean {
18+
if (node == null) return false
19+
val currentSum = sum + node.`val`
20+
if (node.left == null && node.right == null) {
21+
return currentSum == targetSum
22+
}
23+
return dfs(node.left, currentSum, targetSum) || dfs(node.right, currentSum, targetSum)
24+
}
25+
26+
fun hasPathSum1(root: TreeNode?, targetSum: Int): Boolean {
27+
if (root == null) return false
28+
if (root.left == null && root.right == null && root.`val` == targetSum) return true
29+
return hasPathSum(root.left, targetSum - root.`val`) || hasPathSum(root.right, targetSum - root.`val`)
30+
}
31+
}
32+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /