Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions swift/1448-Count-Good-Nodes-In-Binary-Tree.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//
// 1448-Count-Good-Nodes-In-Binary-Tree.swift
// Question Link: https://leetcode.com/problems/count-good-nodes-in-binary-tree/
//

class Solution {
func goodNodes(_ root: TreeNode?) -> Int {
guard let root = root else { return 0 }
return helper(root, Int.min)
}

func helper(_ root: TreeNode?, _ lastVal: Int) -> Int {
guard let root = root else { return 0 }

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can make in this way

let i = root.val >= lastVal ? 1 : 0
let left = helper(root.left, max(lastVal, root.val))
let right = helper(root.right, max(lastVal, root.val))
return i + left + right

And using let more profitable for compiler

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great suggestion. Updated in most recent commit.

if root.val >= lastVal {
var left = helper(root.left, max(lastVal, root.val))
var right = helper(root.right, max(lastVal, root.val))
return 1 + left + right
} else {
var left = helper(root.left, max(lastVal, root.val))
var right = helper(root.right, max(lastVal, root.val))
return left + right
}
}
}