Skip to content

Commit fd465a1

Browse files
authored
Merge pull request #1229 from nprepaci/1448-CountGoodNodesInBinaryTree-Swift
1448-Count Good Nodes in Binary Tree -- SWIFT
2 parents 71d4c5c + 18a6f07 commit fd465a1

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//
2+
// 1448-Count-Good-Nodes-In-Binary-Tree.swift
3+
// Question Link: https://leetcode.com/problems/count-good-nodes-in-binary-tree/
4+
//
5+
6+
class Solution {
7+
func goodNodes(_ root: TreeNode?) -> Int {
8+
guard let root = root else { return 0 }
9+
return helper(root, Int.min)
10+
}
11+
12+
func helper(_ root: TreeNode?, _ lastVal: Int) -> Int {
13+
guard let root = root else { return 0 }
14+
let i = root.val >= lastVal ? 1 : 0
15+
let left = helper(root.left, max(lastVal, root.val))
16+
let right = helper(root.right, max(lastVal, root.val))
17+
return i + left + right
18+
}
19+
}

0 commit comments

Comments
 (0)